if(xmlHttp.readyState==4)的错误原因
why error with if (xmlHttp.readyState == 4)
我之前问过一个关于xmlHttp.send()
代码不起作用的问题。我以为我已经全部解决了,但现在我又遇到了一个问题。
在handleServerResponse()
函数中,代码在if (xmlHttp.readyState == 4) and if (xmlHttp.readyState == 200)
中出错。它为什么这么做?JavaScript下有一个示例php代码。
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>';
您必须在onreadystatechange
事件回调中使用this
,而不是使用变量(xmlHttp
)
所以你的功能是:
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'
})();
xmlHttp.readyState
不能为200。您应该使用xmlHttp.status
。
xmlHttp.readyState
具有XMLHttpRequest的状态XMLHttpRequest对象
当xmlHttp.readyState
为3或4时,xmlHttp.status
将可用。可用时,xmlHttp.status
应表示HTTP状态代码。
相关文章:
- Node.js v6.2.0类扩展不是函数错误
- Jquery菜单操作不稳定,定位不正确,存在一般错误
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 试图在引导模式内动态生成图表,得到offsetWidth错误
- 为什么会出现错误;未捕获的类型错误:undefined不是函数;
- 我如何修复包含在captcha的addthis中的错误
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- Webpack/Rect:遵循egghead.io教程,但出现错误:您可能需要一个合适的加载程序来处理此文件类型
- CKFinder 3为所选文件返回错误的URL
- 同位素库错误:未捕获错误无布局模式包装生产线8
- 铬:“;未捕获的语法错误:意外的标记:"
- 如何通过自己获得Chrome扩展的用户反馈/错误报告
- 相位器状态未捕获参考错误
- /undefined在我的404错误日志中多次出现
- xmlHttp.responseText未知错误定义
- if(xmlHttp.readyState==4)的错误原因
- 在IE11中设置xmlHttp响应类型为msxml-document会抛出无效状态错误
- 如何抑制javascript错误时,xmlhttp.状态!= 200
- 从PHP加载XML错误:Microsoft.XMLHTTP.DocumentElement为空