I'm trying to make an AJAX GET request, but I simply cannot get it to work. I want to retrieve the HTML source of example.com. I've previously used JQuery to send AJAX requests, but I use JQuery only for its AJAX capabilities so it's a waste to include the 30KB file for one task. What is it that I'm doing wrong?
<script type="text/javascript">
var XMLHttpArray = [
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject("Msxml2.XMLHTTP")},
function() {return new ActiveXObject("Msxml2.XMLHTTP")},
function() {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject(){
var xmlhttp = false;
for(var i=0; i<XMLHttpArray.length; i++){
try{
xmlhttp = XMLHttpArray[i]();
}catch(e){
continue;
}
break;
}
return xmlhttp;
}
function AjaxRequest(url,method){
var req = createXMLHTTPObject();
req.onreadystatechange= function(){
if(req.readyState != 4) return;
if(req.status != 200) return;
return req.responseText;
}
req.open(method,url,true);
req.send(null);
}
function MakeRequst(){
var result=AjaxRequest("http://example.com","get");
alert(result);
}
</script>
Returning a value from your state change handler won't do you any good - that code is waiting for something to happen, and it's invoked from the browser innards as the HTTP request is processed. It's asynchronous .
Instead of expecting a result like that, your state change handler must itself handle the response, as appropriate to your application.
function AjaxRequest(url,method){
var req = createXMLHTTPObject();
req.onreadystatechange= function(){
if(req.readyState != 4) return;
if(req.status != 200) return;
alert(req.responseText);
}
req.open(method,url,true);
req.send(null);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.