通过参数AJAX PHP JAVASCRIPT传递变量

时间:2015-06-01 19:41:56

标签: javascript php ajax

我正在尝试编写一个简单的AJAX代码,让它通过一个简单的数组进行搜索,并将结果输出到屏幕,并且在我尝试通过参数传递变量之前它可以工作,但现在它不是由于某种原因,通过参数传递变量。请看一下:

  

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>

1 个答案:

答案 0 :(得分:4)

尝试在不同的阶段添加console.log(variable)来检查变量的当前状态,可能是get变量与encodeURIComponent有问题,或者可能没有进入关于流程功能的if