【发布时间】:2017-08-05 08:41:13
【问题描述】:
我正在关注 newboston ajax 教程,但遇到了错误。 我已经给出了错误的快照。我正在使用 wamp 服务器并在 chrome 浏览器上运行它。
谁能帮帮我?
index.html
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf=8" http-equiv="encoding">
<script type="text/javascript" src="food.js"></script>
</head>
<body onload="process()">
<h2>....Food Shop...</h2>
<input type="text" id="userinput" placeholder="enter the food u want" value="banana">
<div id="underinput" />
</body>
</html>
food.js
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObjects){
try{
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try{
xmlHttp= new XMLHttpRequest();
}catch(e)
{
xmlHttp=false;
}
}
if(!xmlHttp)
{
alert("cant create the object");
}
else{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
food=encodeURIComponent(document.getElementById("userinput").value);
xmlHttp.open("GET","foodstore.php?food=" + food,true);
xmlHttp.onreadystatechange= handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
message = xmlHttp.responseXML.documentElement.firstChild.data;
document.getElementById("underinput").innerHTML= '<span style="color:blue">' + message + '</span>';
setTimeout('process()',1000);
}else{
alert('something wrong...');
}
}
}
foodstore.php
<?php
error_reporting(E_ALL);
int_set('display_errors',true)
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF=8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray= array('banana','apple','mango');
if(in_array($food,$foodArray)){
echo 'we do have'.$food;
}
else if($food ==''){
echo 'enter the food';
}
else{
echo 'sorry we do not have'.$food;
}
echo '</response>';
?>
【问题讨论】:
-
它告诉你
xmlHttp.responseXML是空的,所以你应该记录它,看看服务器真正返回了什么 -
你能告诉我如何登录
-
console.log( xmlHttp.responseXML )和console.log( typeof xmlHttp.responseXML ) -
那个 ajax 函数现在已经非常过时了——如果你只是在学习 ajax,你也许应该看看
fetchapi (developer.mozilla.org/en/docs/Web/API/Fetch_API) -
不工作还是同样的问题
标签: javascript php ajax