Ajax基础教程(3)
我们现在将整个过程完整地做一次,发送一个简单的HTTP请求. 我们用javascript请求一个HTML文件, test.html, 文件的文本内容为"I'm a test.".然后我们"alert()"test.html文件的内容.
var http_request = false;
function makeRequest(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('GET', url, true);
http_request.send(null); }
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
style="cursor: pointer; text-decoration: underline"
onclick="makeRequest('test.html')">
Make a request
本例中:
• 用户点击浏览器上的"请求"链接;
• 接着函数makeRequest()将被调用.其参数 – HTML文件test.html在同一目录下;
• 这样就发起了一个请求.onreadystatechange的执行结果会被传送给alertContents();
• alertContents()将检查服务器的响应是否成功地收到,如果是,就会"alert()"test.html文件的内容.
相关新闻>>
- 发表评论
-
- 最新评论 更多>>