我正在尝试检测我的UIWebView中何时完成任何ajax调用。我在这个答案中修改了代码:JavaScript detect an AJAX event尽我所能。这是我的尝试:
var s_ajaxListener = new Object();
s_ajaxListener.tempOnReadyStateChange = XMLHttpRequest.prototype.onreadystatechange;
s_ajaxListener.callback = function () {
window.location='ajaxHandler://' + this.url;
};
XMLHttpRequest.prototype.onreadystatechange = function() {
alert("onreadystatechange called");
s_ajaxListener.tempOnReadyStateChange.apply(this, arguments);
if(s_ajaxListener.readyState == 4 && s_ajaxListener.status == 200) {
s_ajaxListener.callback();
}
}
我将此注入到webView中,但警报从未触发。如果我在脚本的开头或结尾放置一个警报,它会触发,所以我很确定没有语法错误。
我不是一个JS人,所以我希望这是一个微不足道的问题。
答案 0 :(得分:4)
在onreadystatechange
中放置通用XMLHttpRequest.prototype
对我不起作用。但是,您链接到的代码可以很容易地适应在发生该事件时调用自定义函数:
var s_ajaxListener = {};
s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open;
s_ajaxListener.tempSend = XMLHttpRequest.prototype.send;
// callback will be invoked on readystatechange
s_ajaxListener.callback = function () {
// "this" will be the XHR object
// it will contain status and readystate
console.log(this);
}
XMLHttpRequest.prototype.open = function(a,b) {
if (!a) var a='';
if (!b) var b='';
s_ajaxListener.tempOpen.apply(this, arguments);
s_ajaxListener.method = a;
s_ajaxListener.url = b;
if (a.toLowerCase() == 'get') {
s_ajaxListener.data = b.split('?');
s_ajaxListener.data = s_ajaxListener.data[1];
}
}
XMLHttpRequest.prototype.send = function(a,b) {
if (!a) var a='';
if (!b) var b='';
s_ajaxListener.tempSend.apply(this, arguments);
if(s_ajaxListener.method.toLowerCase() == 'post')s_ajaxListener.data = a;
// assigning callback to onreadystatechange
// instead of calling directly
this.onreadystatechange = s_ajaxListener.callback;
}