2015-06-01 36 views
-2

我想写一个简单的AJAX代码来让它通过一个简单的数组进行搜索,并将结果输出到屏幕上,并且它在我试图通过变量传递参数,但现在由于某种原因,它不通过参数传递变量。请看看:通过参数传递变量AJAX PHP JAVASCRIPT

functions.js:

var xmlHttp = createXmlHttpRequestObject(); 

//****************************************************************AJAX 

function createXmlHttpRequestObject() { 
    var xmlHttp; 

    if (window.ActiveXObject) { 
     try { 
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } catch (e) { 
      xmlHttp = false; 
     } 
    } else { 
     try { 
      xmlHttp = new XMLHttpRequest(); 
     } catch (e) { 
      xmlHttp = false; 
     } 
    } 

    if (!xmlHttp) 
     alert("Not xmlHttp!")else 
      return xmlHttp; 
} 

//****************************************************************AJAX 

function process(IDName, passTo, output) { 
    if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) { 
     get = encodeURIComponent(document.getElementById(IDName).value); 
     xmlHttp.open("GET", passTo + get, true); 
     xmlHttp.onreadystatechange = handleServerResponse(output); 
     xmlHttp.send(null); 
    } else { 
     setTimeout('process()', 1000); 
    } 
} 

//****************************************************************AJAX 

function handleServerResponse(output) { 
    if (xmlHttp.readyState == 4) { 
     if (xmlHttp.status == 200) { 
      xmlResponse = xmlHttp.responseXML; 
      xmlDocumentElement = xmlResponse.documentElement; 
      message = xmlDocumentElement.firstChild.data; 
      document.getElementById(output).innerHTML = message; 
      setTimeout('process()', 1000); 
     } else { 
      alert('xmlHttp.status does not equal 200!'); 
     } 
    } 
} 

foodstore.php:

<?php 
header('Content-Type: text/xml'); 
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'; 

echo '<response>'; 
$food = $_GET['food']; 
$foodArray = array('tuna','bacon','beef','ham'); 

if(in_array($food,$foodArray)) 
    echo 'We do have '.$food.'!'; 
elseif ($food=='') 
    echo 'Enter a food'; 
else 
    echo 'Sorry punk we dont sell no '.$food.'!'; 

echo '</response>'; 
?> 

test5.html:

<!DOCTYPE html> 
<html> 
<head> 
    <script type="text/javascript" src="functions.js"></script> 
</head> 
<body onload="process('userInput','foodstore.php?food=','underInput')"> 
    <h3>The Chuff Bucker</h3> 
    Enter the food you would like to order: 
    <input type="text" id="userInput" /> 
    <div id="underInput" /> 
</body> 
</html> 
+0

坦率地说,除了这个问题之外,为什么不使用其中的一个_many many_ JS库,它会为你做这些工作呢? –

+0

@JonStirling JS库? – iscattered

+0

jQuery,Angular,MooTools。名单继续。 –

回答

4

尝试在不同阶段加入console.log(variable)检查变量的当前状态,可能是你有问题与get变量与encodeURIComponent也许它没有进入到if的处理功能。