XMLHttpRequest 的使用······

// JavaScript Document


/*创建XMLHttpRequest对象
*这段代码的核心分为三步:
1、建立一个变量 xmlHttp 来引用即将创建的 XMLHttpRequest 对象。 
2、尝试在 Microsoft 浏览器中创建该对象: 
1)尝试使用 Msxml2.XMLHTTP 对象创建它。

 
2)假设失败,再尝试 Microsoft.XMLHTTP 对象。 
3、假设仍然没有建立 xmlHttp。则以非 Microsoft 的方式创建该对象。 

*/


function createXmlHttp(){
var xmlHttp = false;
try {
//在 Microsoft 浏览器上创建 XMLHttpRequest 对象
//假设使用较新版本号的 Internet Explorer,则须要使用对象 Msxml2.XMLHTTP
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
//较老版本号的 Internet Explorer 则使用 Microsoft.XMLHTTP
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
//在非 Microsoft 浏览器上创建 XMLHttpRequest 对象
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}

/*发出请求:
在全部 Ajax 应用程序中基本都雷同的流程:


1、从 Web 表单中获取须要的数据。 
2、建立要连接的 URL。 
3、打开到server的连接。 
4、设置server在完毕后要执行的函数。 
5、发送请求。 
*/

function callServer() {
  // Get the city and state from the web form
  var city = document.getElementById("city").value;
  var state = document.getElementById("state").value;
  // Only go on if there are values for both fields
  if ((city == null) || (city == "")) return;
  if ((state == null) || (state == "")) return;
  // Build the URL to connect to
  var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state);
  // Open a connection to the server
  xmlHttp.open("GET", url, true);
  // Setup a function for the server to run when it's done
  xmlHttp.onreadystatechange = updatePage;
  // Send the request
  xmlHttp.send(null);
}
/*xmlHttp的 onreadystatechange 属性能够告诉server在执行完毕后做什么。
由于代码没有等待server,必须让server知道怎么做以便您能作出响应。
在这个演示样例中,假设server处理完了请求,一个特殊的名为 updatePage() 的方法将被触发。



须要特别注意的是该属性在代码中设置的位置 —— 它是在调用 send() 之前 设置的。
发送请求之前必须设置该属性,这样server在回答完毕请求之后才干查看该属性
*/

function updatePage() {
 if (request.readyState == 4)
if (request.status == 200)
alert("Server is done!");
else if (request.status == 404)
alert("Request URL does not exist");
else
alert("Error: status code is " + request.status);
}





























posted @ 2016-01-05 16:04  hrhguanli  阅读(247)  评论(0编辑  收藏  举报