JQuery可以从其他JavaScript调用AJAX调用吗?
我需要在购物车中构建一个function,当购物内容发生变化时(例如,产品被删除),该购物车使用AJAX从服务器检索模板的更新副本。 我不能修改服务器端代码,或者首先使购物车工作的JavaScript。 (我不知道,但它就是这样)
我想要做的是每次购物车更新时运行我自己的JavaScript。 我想知道是否可以监听AJAX调用 ,并在每次调用时运行我的代码。
要跟踪HTML文档上的所有AJAX调用,您可以覆盖XMLHttpRequest
原型。 这样,您可以查看对XMLHttpRequest
对象的方法的操作。
这是一个小示例代码:
var open = window.XMLHttpRequest.prototype.open, send = window.XMLHttpRequest.prototype.send, onReadyStateChange; function openReplacement(method, url, async, user, password) { var syncMode = async !== false ? 'async' : 'sync'; console.warn( 'Preparing ' + syncMode + ' HTTP request : ' + method + ' ' + url ); return open.apply(this, arguments); } function sendReplacement(data) { console.warn('Sending HTTP request data : ', data); if(this.onreadystatechange) { this._onreadystatechange = this.onreadystatechange; } this.onreadystatechange = onReadyStateChangeReplacement; return send.apply(this, arguments); } function onReadyStateChangeReplacement() { console.warn('HTTP request ready state changed : ' + this.readyState); if(this._onreadystatechange) { return this._onreadystatechange.apply(this, arguments); } } window.XMLHttpRequest.prototype.open = openReplacement; window.XMLHttpRequest.prototype.send = sendReplacement;
通过此示例,对于每个AJAX调用,您将在JavaScript控制台中收到警告。
它不是jQuery脚本,但您可以根据需要使用jQuery。
这个解决方案可能不适用于IE 6或更早版本,但它适用于FF,IE7 +,Chrome,Opera,Safari ……
我更喜欢这个解决方案。
$(document).ajaxComplete(function(event,request, settings){ // Your code here });
我的朋友你可以用Jquery轻松地做到这一点(正如你告诉过你正在使用Jquery)
(对于那些没有使用的人,他们可以在ajax函数下的Jquery库代码中驱动来查看本机代码:’))
$(document).bind("ajaxSend", function(){ $("#loading").show(); }).bind("ajaxComplete", function(){ $("#loading").hide(); });
这是从jquery官方api文档中获取的代码片段(参见全球事件部分)
您无法收听,但可以使用定期更新程序插件。 看下面的内容:
http://plugins.jquery.com/plugin-tags/periodic-updater
这采用了在XHR原型中添加回调的相同方法,但没有在原型上设置任何新属性或编写我们自己的事件链机制。 我认为这不太可能引入冲突。
(function() { // Reference to the original prototype method we're overriding var originalOpen = XMLHttpRequest.prototype.open; // Override prototype.open to add a custom callback whenever a request is opened XMLHttpRequest.prototype.open = function() { this.addEventListener('loadend', customCallback); // Execute the original prototype.open without affecting its execution context originalOpen.apply(this, arguments); }; // All instances of XMLHttpRequest will execute this callback once on readyState 4 var customCallback = function () { // In this context, `this` refers to the XHR instance that just completed console.log(this); // Remove the invoking listener to prevent duping on multiple calls to .open this.removeEventListener('loadend', customCallback); } }());
这在IE <= 8(不支持.addEventListener()
)中不起作用