How Create Ajax Request Manually?
Solution 1:
If all you want is a basic request then you can do it easily without any libraries with the functions find here http://www.quirksmode.org/js/xmlhttp.html
functionsendRequest(url,callback,postData) {
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
req.setRequestHeader('User-Agent','XMLHTTP/1.0');
if (postData)
req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
// alert('HTTP error ' + req.status);return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
varXMLHttpFactories = [
function () {returnnewXMLHttpRequest()},
function () {returnnewActiveXObject("Msxml2.XMLHTTP")},
function () {returnnewActiveXObject("Msxml3.XMLHTTP")},
function () {returnnewActiveXObject("Microsoft.XMLHTTP")}
];
functioncreateXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
Solution 2:
I'm having to guess at what you mean, but basically, you use the XMLHttpRequest
object to do ajax requests. It's a Microsoft innovation that other browsers have adopted and which is now in the process of being standardized. It looks like this in modern browsers:
functionsendRequest() {
var request = newXMLHttpRequest();
request.open('GET', '/Home/Start', false);
request.onreadystatechange = handleStateChange;
request.send(null);
functionhandleStateChange() {
if (request.readyState === 4) {
// The request is complete; did it work?if (this.status >= 200 && this.status < 300) {
// Yes, you can use the data on request.responseText// or (for requests with XML replies) request.responseXML// In our case, let's say we want to put all of the text// into the element with the `id` "js_script":var elm = document.getElementById("js_script");
elm.innerHTML = request.responseText;
}
}
}
}
That's obviously quite simplified. On old browsers, you have to do a couple of checks around creating the object (new XMLHttpRequest
doesn't work on IE7, for instance, but there are ways to do it on IE7.)
The complications around creating the object on older browsers are one of many, many reasons I recommend using any of the decent JavaScript libraries like jQuery, Prototype, YUI, Closure, or any of several others. They smooth over browser differences for you, add a lot of utility functionality, and let you concentrate on getting your specific task done rather than worrying about (say) HTTP status codes. That's not to say there isn't a time and place for doing things without libraries — of course there is — just that normally, one can be more productive building on the work of others than going completely on your own.
Post a Comment for "How Create Ajax Request Manually?"