没有框架的javascript ajax请求 [英] javascript ajax request without framework
问题描述
有谁知道如何在不使用 jQuery 等 javascript 框架的情况下制作跨浏览器的 ajax 请求函数?
Does anyone know how to make ajax request function that works cross-browser WITHOUT using a javascript framework like jQuery, etc.?
推荐答案
XMLHttpRequest
对象实际上使用起来并不复杂.为了广泛兼容,您必须玩一些游戏来创建对象,但之后对于简单的操作就相当简单了.
The XMLHttpRequest
object isn't actually all that complicated to use. To be broadly compatible, you have to play a bit of a game to create the object, but after that it's fairly straightforward for simple operations.
Microsoft 在 MSDN 页面上有示例XMLHttpRequest
,包括以跨浏览器方式创建对象的函数,支持早期版本的IE.这是他们的例子:
Microsoft has examples on the MSDN page for XMLHttpRequest
, including a function for creating the object in a cross-browser way that supports early versions of IE. Here's their example:
function getXMLHttpRequest()
{
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
}
else {
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(ex) {
return null;
}
}
}
function handler()
{
if (oReq.readyState == 4 /* complete */) {
if (oReq.status == 200) {
alert(oReq.responseText);
}
}
}
var oReq = getXMLHttpRequest();
if (oReq != null) {
oReq.open("GET", "http://localhost/test.xml", true);
oReq.onreadystatechange = handler;
oReq.send();
}
else {
window.alert("AJAX (XMLHTTP) not supported.");
}
我并不是建议上述示例是最佳实践(Microsoft 似乎有他们的 MSDN 示例主要由非常非常缺乏经验的工程师编写),但它为您提供了一个起点.例如,上面要求响应状态为 200 表示成功,当然 HTTP 规范明确指出 200 <= n <= 299 范围内的任何内容都是成功".
I'm not suggesting the above exemplifies best practices (Microsoft seems to have their MSDN examples largely written by very, very inexperienced engineers), but it gives you a starting point. For instance, the above requires that the response status be 200 for success, where of course the HTTP specification is clear that anything the 200 <= n <= 299 range is "success".
这篇关于没有框架的javascript ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!