我是AJAX的新手,並且學習它。我正在我的HTML文本框中搜索食品,並試圖與服務器通信以瞭解該項目是否可用。該項目的相應狀態應顯示在文本框下方的div標記中,但未顯示。AJAX邏輯不起作用
我沒有研究過的jQuery但並想知道下面的事情:
如何從使用AJAX和JavaScript明文服務器的響應,並在下面的div標籤顯示它文本框(建議在代碼中進行更改)。
我應該在JavaScript代碼中發送POST方法中的AJAX請求(我知道PHP代碼中的更改)應做出什麼改變?
//index.html
<head>
<script type="text/javascript" src="food.js">
</script>
</head>
<body>
<h3>The Cheff's Place</h3>
Enter the food you want to order
<input type="text" id="userInput" name="input" onkeypress="sendInfo()"></input>
<div id="underInput"></div>
</body>
</html>
//food.js
var request;
function sendInfo() {
var v = document.getElementById("userInput").value;
var url = "index.php?food=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.readyState == 0 || request.readyState == 4) {
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send(null);
} catch (e) {
alert("Unable to connect to server");
}
}
}
function getInfo() {
if (request.readyState == 4) {
if (request.status == 200) {
var val = request.responseText;
document.getElementById('underInput').innerHTML = val;
}
}
}
//index.php
<?php
header('Content-Type: text/plain');
$food = $_GET['food'];
$foodArray = array("paneer", "butter", "chicken", "tandoori", "dal");
if (in_array($food, $foodArray))
{
echo "We do have " .$food;
}
elseif($food == "")
{
echo "Kindly enter some food";
}
else
{
echo "We do not sell " .$food;
}
?>
請嘗試下面的例子。你可以在請求返回到'xhr.responseText'後獲得響應https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange –
我試過了,但沒有幫助。 如果您想在您的最後嘗試上面的代碼並讓我知道代碼中所做的更改將會很有幫助。 – Krishna
在food.js中,這個條件永遠不會發生,因爲請求不會在那個時候發送。 'if(request.readyState == 0 || request.readyState == 4)'所以沒有代碼在那裏執行 –