7

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();
    }
}

これを webView に挿入していますが、アラートは発生しません。スクリプトの最初または最後にアラートを配置すると、アラートが発生するので、構文エラーがないことはほぼ確実です。

私はJSの男ではないので、これが些細な問題であることを願っています.

4

1 に答える 1

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;
}

http://jsfiddle.net/s6xqu/

于 2013-09-24T17:16:49.933 に答える