基本上我想做的是有一个文本字段,用户可以在其中输入食品,并且当他们输入消息时更新以说明所述商品是否有货(通过联系数据库)。
我的 xml 的 php 代码:
require 'connect.php';
header('Content-Type: text/xml');
echo "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>";
echo '<response>';
if (isset($_GET['foodInput'])&&!empty($_GET['foodInput'])) {
extract($_GET);
$sql = "SELECT * FROM food WHERE name=:foodInput";
$stmt = $db -> prepare($sql);
if ($stmt ->execute(array(':foodInput'=>$foodInput))) {
if ($stmt -> rowCount()>0) {
$results = $stmt -> fetch(PDO::FETCH_OBJ);
echo 'Yes, we do in fact have '.$results->name.'.';
}else{ echo 'No, '.$foodInput.' is not available champ.'; }
}
}else{ echo 'Please enter foodstuff.'; }
echo '</response>';
剩下的我的 Javascript:
function createHttp(){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
};
return xmlhttp;
}
var xmlhttp = createHttp();
function handleServerResponse(){
if(xmlhttp.readyState==4){
if (xmlhttp.status==200) {
xmlResponse = xmlhttp.responseXML;
xmlDoc = xmlResponse.documentElement;
message = xmlDoc.firstChild.data;
document.getElementById('updated').innerHTML = message;
setTimeout(process, 1000);
};
}else{
alert('Something is amiss');
}
}
function process(){
if (xmlhttp.readyState==4||xmlhttp.readyState==0){
food = encodeURIComponent(document.getElementById('food').value);
xmlhttp.open('GET', 'include/foodstore.php?foodInput='+food,true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.send();
}else{
setTimeout(process, 1000);
}
}
一旦进程初始化,当 readyState 不再是 4 时,我会收到警告,出现错误消息。我输入了一个 console.log(xmlhttp.readyState),结果日志基本上是 1234123412341234 等。所以而不是坚持到 4 点它会有所作为,否则呢?老实说,我不是特别确定 readyState 是什么。
当我删除此警报并允许我输入文本时,它会根据目的需要进行更新。但是一旦警报重新打开,宾果游戏又来了。
有什么建议吗?这个领域真的很新。
谢谢
编辑:HTML
<form action="">
<label for="food">Enter foodstuff:</label>
<input type="text" id="food" name="foodInput" onkeyup="process()"><br>
</form>
<h4 id="updated"></h5>
最佳答案
xmlhttp.open('GET', 'include/foodstore.php?food='+food,true);
此处您将值分配给名为 food
的变量,但在 php 中您试图获取名为 foodInput
的变量的值
if (isset($_GET['foodInput'])&&!empty($_GET['foodInput'])) {
编辑:
所以只需将 xmlhttp.open
更改为:
xmlhttp.open('GET', 'include/foodstore.php?foodInput='+food,true);
关于xmlhttp readystates,不同的状态如下:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
在你的情况下,我猜你想将 else 子句放在这个 if 中:
if (xmlhttp.status==200) { ... }
关于JavaScript ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29459322/