2017-10-18 102 views
0

我是AJAX的新手,并且学习它。我正在我的HTML文本框中搜索食品,并试图与服务器通信以了解该项目是否可用。该项目的相应状态应显示在文本框下方的div标记中,但未显示。AJAX逻辑不起作用

我没有研究过的jQuery但并想知道下面的事情:

  1. 如何从使用AJAX和JavaScript明文服务器的响应,并在下面的div标签显示它文本框(建议在代码中进行更改)。

  2. 我应该在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; 
    } 
?> 
+0

请尝试下面的例子。你可以在请求返回到'xhr.responseText'后获得响应https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange –

+0

我试过了,但没有帮助。 如果您想在您的最后尝试上面的代码并让我知道代码中所做的更改将会很有帮助。 – Krishna

+0

在food.js中,这个条件永远不会发生,因为请求不会在那个时候发送。 'if(request.readyState == 0 || request.readyState == 4)'所以没有代码在那里执行 –

回答

0

我跑你的代码。它工作正常。用onkeyup替换onkeypress。

<input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input> 

使用jQuery(假设你已经包括jQuery的文件或CDN):

包括脚本标签在身体的结束下面的代码片断。

$("#userInput").keyup(function(){ 
     $.get("index.php", { food: $("#userInput").val() }) 
      .done(function(data) { 
       $("#underInput").html(data) 
      }) 
    }); 
+0

我不是jquery先生的经文,所以任何关于javascript的帮助都会有所帮助。 – Krishna

+0

更换onkeyup后它现在工作吗? –

+0

我尝试使用onkeyup,但它仍然无法正常工作。 我没有包含jQuery代码。 如果你想在你的最后尝试上面的代码,并让我知道如果不工作,代码中所做的更改将会有所帮助。 – Krishna