2017-10-18 101 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