未调用onreadystatechange的XMLHttpRequest原型

Lan*_*nce 7 javascript ajax uiwebview

我正试图检测我的UIWebView中何时完成任何ajax调用.我在这个答案中修改了代码:JavaScript尽我最大的能力检测AJAX事件.这是我的尝试:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在将其注入webView,但警报从未触发.如果我在脚本的开头或结尾放置一个警报,它会触发,所以我很确定没有语法错误.

我不是一个JS人,所以我希望这是一个微不足道的问题.

bfa*_*tto 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;
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/s6xqu/