我之前问了一个关于xmlHttp.send()
代码的问题。我以为我已经解决了所有问题,但现在我又遇到了另一个问题。
在handleServerResponse()
函数中,代码在if (xmlHttp.readyState == 4) and if (xmlHttp.readyState == 200)
中出错。它为什么这样做?一个示例PHP代码在JavaScript下。
var xmlHttp = createXmlHttpRequestObject();
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("cant create that object hos");
}else{
return xmlHttp;
}
}
function newuser() {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
name = encodeURIComponent(document.getElementById("name").value);
queryString = "name=" + name;
xmlHttp.open("GET", "code/php/core.php?" + queryString, true);
xmlHttp.onreadystatechange = handleServerRespons;
xmlHttp.send();
}else{
setTimeout('newuser()', 1000)
}
}
function handleServerRespons(){
if (xmlHttp.readyState == 4){
if (xmlHttp.readyState == 200){
alert('1234545');
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert(message);
}
}
}
php代码:
$name = $_GET['name'];
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
echo $name;
echo '</response>';
答案 0 :(得分:1)
而不是使用变量(xmlHttp
),您必须在this
事件回调中使用onreadystatechange
所以你的功能将是:
function handleServerRespons() {
if ( this.readyState === 4 && this.status === 200 ) { // and also use "status" here not "readyState"
xmlResponse = this.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert( message );
}
}
或用(function(){...})();
包裹您的代码,如下所示
(function() {
// all your code goes here, so you can use that 'xmlHttp' instead of 'this'
})();
答案 1 :(得分:0)
xmlHttp.readyState
不能为200.您应该使用xmlHttp.status
。
答案 2 :(得分:0)
xmlHttp.readyState
具有XMLHttpRequest The XMLHttpRequest Object
xmlHttp.status
为3或4时, xmlHttp.readyState
可用。可用时xmlHttp.status
应代表HTTP状态代码。