我是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)'所以没有代码在那里执行 –