There are a number of common front-end tasks that many of us never touched the deep, dirty APIs for because our beloved JavaScript frameworks have provided easier ways to work with them. That's why I wrote How JavaScript Event Delegation Works, Do a Basic HTTP Request with Node.js, and scores of tutorials about other low level API posts. Next up is XMLHttpRequest, the API with which we use to make our AJAX calls!
有许多常见的前端任务,我们许多人从未接触过这些深层次的,肮脏的API,因为我们钟爱JavaScript框架提供了使用它们的简便方法。 这就是为什么我写了《 JavaScript事件委托的工作 原理》 ,《 使用Node.js进行基本HTTP请求》以及关于其他一些低级API帖子的教程。 接下来是XMLHttpRequest,我们用来进行AJAX调用的API!
检索XHR对象 (Retrieving the XHR Object)
Unlike most APIs, getting the core component is actually a bit of work since Internet Explorer used to require an ActiveX component to get AJAX to work:
与大多数API不同,由于Internet Explorer过去要求ActiveX组件才能使AJAX正常工作,因此获取核心组件实际上需要一些工作:
var request;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e) {}
}
}
Bleh; the code is ugly but that's what you should expect behind the curtain, right?
布雷 代码很丑陋,但这就是您应该期待的,对吧?
发出请求 (Making a Request)
Making a request requires two function calls:
发出请求需要两个函数调用:
request.open('GET', 'https://davidwalsh.name/ajax-endpoint', true);
request.send(null);
The open call defines the request type (get
, post
, etc.) and the send method executes the request. Simple enough! Adding custom headers is simple too:
open调用定义请求类型( get
, post
等),并且send方法执行请求。 很简单! 添加自定义标头也很简单:
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
要求回电 (Request Callbacks)
Of course making requests is somewhat useless if you don't handle the result, and there are two ways to set a callback:
当然,如果您不处理结果,则发出请求会毫无用处,并且有两种方法可以设置回调:
// state changes
request.onreadystatechange = function() {
if(request.readyState === 4) { // done
if(request.status === 200) { // complete
console.log(request.responseText)
}
}
};
// addEventListener
function callbackFn(e) {
// Handle each event
}
request.addEventListener("progress", callbackFn, false);
request.addEventListener("load", callbackFn, false);
request.addEventListener("error", callbackFn, false);
request.addEventListener("abort", callbackFn, false);
Choose whichever method you'd like but the addEventListener
method is probably more elegant.
选择您想要的任何方法,但addEventListener
方法可能更优雅。
That's my simple introduction into creating simple AJAX requests with the native XMLHttpRequest API. For further information about common AJAX tests, like sending form data, check out the Mozilla Developer Network!
那是我对使用本机XMLHttpRequest API创建简单AJAX请求的简单介绍。 有关发送表单数据的常见AJAX测试的更多信息,请访问Mozilla开发人员网络 !