我希望用戶在文本字段中輸入值。然後,根據輸入到文本字段中的內容,向php文件發出請求,該文件將生成輸入的特定狀態的簡要說明。如何從輸入中獲取值並使AJAX產生響應
這是我的。
<html>
<head>
<script>
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest)
{
XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID)
{
if (XMLHttpRequestObject)
{
var obj = document.getElementById(divID);
obj.innerHTML = "";
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange =
function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
<form>
<p>Enter State:</p>
<input type="text" name="State">
<br>
<br>
<input type="button" value="Submit" onclick="getData('k5a.php?state=2', 'targetDiv')">
</form>
<div id="targetDiv">
<p>The state Info will appear here.</p>
</div
所以PHP文件看起來像
<?php
header("Cache-Control: post-check=1, pre-check=2");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
$choice = $_GET['state'];
switch ($choice)
{
case 1:
echo "California is the most populous state in the United States and the third most extensive by area. Located on the western (Pacific Ocean) coast of the U.S., California is bordered by the other U.S. states of Oregon, Nevada, and Arizona and shares an international border with the Mexican state of Baja California.";
break;
case 2:
echo "Florida is a state located in the southeastern region of the United States. It is bordered to the west by the Gulf of Mexico, to the north by Alabama and Georgia, to the east by the Atlantic Ocean, and to the south by the Straits of Florida and Cuba. Florida is the 22nd most extensive, the 3rd most populous, and the 8th most densely populated of the U.S. states.";
break;
case 3:
echo "New York is the most populous city in the United States. With an estimated 2015 population of 8,550,405 distributed over a land area of about 302.6 square miles. New York City is also the most densely populated major city in the United States. Located at the southern tip of the state of New York, the city is the center of the New York metropolitan area, one of the most populous urban agglomerations in the world.";
break;
}
?>
我所要的輸出是在任何狀態用戶輸入信息。我被困在如何執行switch語句/ onclick方法。
你能描述一下哪些工作沒有成功嗎? ? – shofstetter
@shofstetter如何獲得與switch語句對應的輸入值...即輸入California,加州的信息將顯示 – Ryan
而不是案例1:'放入案例'California':'等等等等 – eeetee