Javascript ajax request


Javascript ajax request

>基本上,我要做的是有一个文本字段,用户在其中输入食品,当他们输入消息时,更新以说明所述物品是否有库存(通过联系数据库(。

我的 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 时,会出现错误消息。我输入了一个控制台.log(xmlhttp.readyState(,结果日志基本上是1234123412341234等。所以与其在 4 点坚持下去,它会做点什么,否则?老实说,我不是特别确定 readyState 是什么。

当我删除此警报并允许我输入文本时,它会根据目的需要更新。但是一旦警报重新打开,宾果游戏就会再次出现。

有什么建议吗?这个领域真的很新。

谢谢

编辑: 网页

<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 就绪状态,不同的状态如下:

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 (xmlhttp.status==200) { ... }

您仅在 DOM 加载上运行 process 函数,但当输入的值随 onkeyup="process()" 更改时,您应该调用它。