我正在关注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>';
?>
答案 0 :(得分:0)
我认为,错误在于生成XML数据的PHP代码。当我尝试使用该代码时,当我尝试使用javascript解析xml时出现错误。我得到的错误是:
此页面包含以下错误:第34行第1行的错误: 字符串未关闭期待&#34;或者&#39;下面是页面的渲染 到第一个错误。
当您使用PHP生成xml时,为什么不使用属于核心PHP的正确方法 - 即DOMDocument
?
以下是您的代码的修改版本,应该返回您正在努力的响应。
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && !empty( $_GET['food'] ) ){
/* Filter the input data */
$food = filter_input( INPUT_GET, 'food', FILTER_SANITIZE_STRING );
/* an array of foodstuffs */
$foods = array('banana','apple','mango','orange','plum','peach','cherry','kiwi','grape','lemon');
/* Construct the response message based upon existance of food */
$message = empty( $food ) ? 'enter the food' : ( in_array( $food, $foods ) ? 'We do have '.$food : 'Sorry, we do not have '.$food );
/* using DOMDocument to output a correctly formed XML document */
$dom=new DOMDocument('1.0', 'utf-8');
$dom->appendChild( $dom->createElement( 'response', $message ) );
$xml = $dom->saveXML();
$dom=null;
/* send the response */
header('Content-Type: application/xml');
exit( $xml );
}
?>
<!doctype html>
<html>
<head>
<title>Ajax and XML</title>
<script>
/* lightweight utility function for making ajax requests */
function ajax(url,method,params,callback){
var xhr=new XMLHttpRequest();
xhr.onload=function(){
callback.call( this, this.response )
};
xhr.onerror=function(e){
console.log(e)
};
var payload=[];
for( var n in params )payload.push( n + '=' + params[ n ] );
var p;
switch( method.toLowerCase() ){
case 'post': p=payload.join('&'); break;
case 'get': url+='?'+payload.join('&'); p=null; break;
}
xhr.open( method.toUpperCase(), url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}
/* utility function to get a parser to process XML data */
function get_parser(str_xml) {
try {
if( window.XMLSerializer && typeof( DOMParser )!='undefined' ) {
var parser = new DOMParser();
return parser.parseFromString(str_xml, 'application/xml');
} else if( typeof( ActiveXObject ) != 'undefined' ) {
var parser = CreateMSXMLDocumentObject();
parser.async='false';
parser.load( str_xml );
return parser;
} else {
var url = 'data:text/xml;charset=utf-8,' + encodeURIComponent( str_xml );
var request = new XMLHttpRequest();
request.open( 'GET', url, false );
request.send( null );
return request.responseXML;
}
} catch( err ) {
console.warn( err );
}
}
function process(){
/*
Change to suit your environment ~ for this demo I use same page ( location.href )
*/
var food = document.querySelector('input[name="food"]').value;
if( food && food!='' ){
//ajax.call( this, 'foodstore.php', 'get', { food:food }, handleServerResponse );
ajax.call( this, location.href, 'get', { food:food }, handleServerResponse );
}
}
/* callback function to process xml response data */
function handleServerResponse(response){
if( response ){
/* parse xml response */
var xml=get_parser( response );
/* get the node which is of interest - only one in this case */
var message = xml.documentElement.textContent;
/* output message to browser */
document.getElementById("underinput").innerHTML= '<span style="color:blue">' + message + '</span>';
}
}
function bindEvents(e){
document.getElementById('bttn').onclick=process;
}
document.addEventListener('DOMContentLoaded', bindEvents,{ passive:true, capture:false } );
</script>
</head>
<body>
<form name='geronimo'>
<label for='food'>Enter Food<input type='text' name='food' placeholder='eg: apple' size=60 /></label>
<input type='button' id='bttn' value='Check' />
<div id='underinput'></div>
</form>
</body>
</html>