发送 AJAX 请求 - 无法开始工作
我正在尝试发出 AJAX GET 请求,但我根本无法让它工作。我想检索 example.com 的 HTML 源代码。我以前使用 JQuery 发送 AJAX 请求,但我使用 JQuery 只是为了它的 AJAX 功能,因此为一项任务包含 30KB 文件是一种浪费。我做错了什么?
<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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从状态更改处理程序返回一个值不会给您带来任何好处 - 该代码正在等待某些事情发生,并且在处理 HTTP 请求时从浏览器内部调用它。它是异步的。
您的状态更改处理程序必须根据您的应用程序本身处理响应,而不是期望这样的结果。
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.