javascript - ajax的onreadystatechange的问题
本文介绍了javascript - ajax的onreadystatechange的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
自己用原生js造了一个轮子
var Ajax = function (config) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.dataType = config.dataType;
xhr.responseType = config.responseType;
xhr.open(config.method,config.url,config.async);
// xhr.onreadystatechange = config.ondone(xhr);
// xhr.onreadystatechange = function () {
// console.log( xhr )
// config.ondone(xhr);
// };
xhr.onerror = function () {
console.info('readyState = ' + xhr.readyState)
console.info('status = ' + xhr.status)
config.onerror;
}
xhr.send(config.data);
}
以下为调用
Ajax({
url:'./',
data:formData,
async:'true',
method:'POST',
dataType:'type',
responseType:'text',
ondone:function (xhr) {
console.log( xhr )
console.log( xhr.readyState )
},
onerror:'',
})
现在的问题是onreadystatechange方法,如果按照第一个写的话congole只会出现一次readyState为1。
如果我用第二个方法的话,是可以正常显示的readyState都能打印出来。
是哪里写错了还是?
解决方案
xhr.onreadystatechange = config.ondone(xhr);
因为你第一种写法其实是相当于执行了一次ondone
函数,执行完xhr.onreadystatechange == null
,null其实就是ondone
函数的返回值。
如果想要将一个函数赋值给xhr.onreadystatechange
,需要这样写:
xhr.onreadystatechange = config.ondone;
虽然这样就无法直接传递参数,所以可以用第二种写法。
这篇关于javascript - ajax的onreadystatechange的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文