錯誤,但在本地沒有工作的服務器上運行時,我得到:AJAX對服務器
TypeError: Cannot read property 'documentElement' of null
我使用AJAX來從一個PHP的XML文件,並把我的HTML DIV的響應。 Javascript文件用於創建AJAX對象並處理服務器響應。
當我在本地運行此代碼時,一切工作正常。 什麼問題?我只上傳相同的文件到服務器,所以它應該在那裏工作?
PHP代碼:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$food = $_GET['food']; //GET/POST to send the data (code to send data inside js file)
$foodArray = array(
'tuna',
'bacon',
'beef',
'meat'
);
if (in_array($food, $foodArray))
echo 'We do have ' . $food;
elseif ($food == '')
echo "AJAX. Server response will be displayed here";
else
echo 'Sorry! We don\'t sell ' . $food;
echo '</response>';
?>
JavaScript代碼:
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function process() {
if (xmlHttp) {
try {
food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET", "foodstore.php?food=" + food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch (e) {
alert(e.toString());
}
} else {
setTimeout('process()', 100);
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
try {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement; // Root element of XML file.
message = xmlDocumentElement.firstChild.data; //Cox it is the only child in the xml document. Data - Output of XML content. So now, message contains the O/P of php.
document.getElementById("underInput").innerHTML = message; //Now that we got the echo statement from the server, we want to store it in our div.
//innerHTML - The html in between the div. The stuff that shows on the web page :)
} catch (e) {
alert(e.toString());
}
setTimeout('process()', 100);
} else {
alert(xmlHttp.statusText);
}
}
HTML:
<body onload="process();">
<div>
Enter a food item you would like to search: e.g. bacon<br>
<input type="text" id="userInput"/><br>
<br>
<div id="underInput"/></div>
OK!我從php文件中更改了標題行。 您的第二個要點;我應該在哪裏添加這個div? 第三點:你是說我應該刪除 echo'<?xml version =「1.0」encoding =「UTF-8」standalone =「yes」?>'; 從PHP文件? 因爲我做到了。而且它仍然會給出同樣的錯誤。 –
第一個可能是*必須*有一個XML名稱空間'attribute =「value」'(xmlns =「http://www.w3.org/1999/xhtml」)。你需要理解用來引用'的通用術語'否則你不會猜到我已經清楚說明了什麼,並且你會更快地接受。正確:對於AJAX加載的內容,您不要使用XML聲明'<?xml version =「1.0」encoding =「UTF-8」standalone =「yes」?>',只是主頁本身。不要使用'documentElement'和**從不**使用innerHTML。 –
John
你的div讓我困惑。我只是想知道爲什麼它不在我自己的知識上在服務器上工作。即使我按照你所提到的做了一切,它仍然在本地工作,但不在服務器上。 –