javascript – 未调用onreadystatechange的XMLHttpRequest原型

前端之家收集整理的这篇文章主要介绍了javascript – 未调用onreadystatechange的XMLHttpRequest原型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正试图检测我的UIWebView中何时完成任何ajax调用.我在这个答案中修改代码JavaScript detect an AJAX event尽我所能.这是我的尝试:
  1. var s_ajaxListener = new Object();
  2. s_ajaxListener.tempOnReadyStateChange = XMLHttpRequest.prototype.onreadystatechange;
  3. s_ajaxListener.callback = function () {
  4. window.location='ajaxHandler://' + this.url;
  5. };
  6.  
  7. XMLHttpRequest.prototype.onreadystatechange = function() {
  8. alert("onreadystatechange called");
  9. s_ajaxListener.tempOnReadyStateChange.apply(this,arguments);
  10. if(s_ajaxListener.readyState == 4 && s_ajaxListener.status == 200) {
  11. s_ajaxListener.callback();
  12. }
  13. }

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

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

解决方法

在XMLHttpRequest.prototype中放置泛型onreadystatechange对我来说不起作用.但是,您链接到的代码可以很容易地适应在发生该事件时调用自定义函数
  1. var s_ajaxListener = {};
  2. s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open;
  3. s_ajaxListener.tempSend = XMLHttpRequest.prototype.send;
  4. // callback will be invoked on readystatechange
  5. s_ajaxListener.callback = function () {
  6. // "this" will be the XHR object
  7. // it will contain status and readystate
  8. console.log(this);
  9. }
  10.  
  11. XMLHttpRequest.prototype.open = function(a,b) {
  12. if (!a) var a='';
  13. if (!b) var b='';
  14. s_ajaxListener.tempOpen.apply(this,arguments);
  15. s_ajaxListener.method = a;
  16. s_ajaxListener.url = b;
  17. if (a.toLowerCase() == 'get') {
  18. s_ajaxListener.data = b.split('?');
  19. s_ajaxListener.data = s_ajaxListener.data[1];
  20. }
  21. }
  22.  
  23. XMLHttpRequest.prototype.send = function(a,b) {
  24. if (!a) var a='';
  25. if (!b) var b='';
  26. s_ajaxListener.tempSend.apply(this,arguments);
  27. if(s_ajaxListener.method.toLowerCase() == 'post')s_ajaxListener.data = a;
  28. // assigning callback to onreadystatechange
  29. // instead of calling directly
  30. this.onreadystatechange = s_ajaxListener.callback;
  31. }

http://jsfiddle.net/s6xqu/

猜你在找的JavaScript相关文章