无框架的JavaScript Ajax请求
时,任何人都知道如何使Ajax请求的功能,工程跨浏览器没有JavaScript框架?
is anyone know how to make ajax request function that works cross-browser WITHOUT javascript framework ?
在 XMLHtt prequest
对象实际上并不是那么复杂使用。要广泛兼容的,你要玩了一下游戏中创建对象,但在它的相当简单的简单的操作。
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.
微软的例子在 MSDN页 XMLHtt prequest
,包括函数用于创建一个支持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.");
}
我并不是说上述例证了最佳实践(微软似乎也有自己的MSDN的例子主要是写的非常非常缺乏经验的工程师),但它给你一个起点。例如,在上述要求的响应状态200为成功,在那里当然HTTP规范很清楚,任何东西的200℃; =正&其中; = 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".