jQuery已经实现了各种 ajax 事件,如 beforeSend 等,但原生的 XMLHttpRequest 并没有这种事件。在没有用 jQuery的情况下,如果想修改 ajax 请求,得做一些特殊的处理。以下是我处理的方法:

XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open;

XMLHttpRequest.prototype.open = function(method, url, async) {

// 用对象便于修改参数

var options = {

method: method,

url: url,

async: async

}

if('function' === typeof window.beforeXMLHttpRequestSend) {

if(!window.beforeXMLHttpRequestSend(this, options)) {

return;

}

}

this._open(options.method, options.url, options.async);

};

window.beforeXMLHttpRequestSend = function(xhr, options) {

//重置参数

options.url == 'reset url';

options.method = 'PUT';

options.async = false;

//禁止发送请求

//return false;

//发送请求

return true;

};

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐