XMLHttpRequest 的使用······
來源:程序員人生 發(fā)布時間:2014-11-14 08:35:26 閱讀次數(shù):2529次
// JavaScript Document
/*創(chuàng)建XMLHttpRequest對象
*這段代碼的核心分為3步:
1、建立1個變量 xmlHttp 來援用行將創(chuàng)建的 XMLHttpRequest 對象。
2、嘗試在 Microsoft 閱讀器中創(chuàng)建該對象:
1)嘗試使用 Msxml2.XMLHTTP 對象創(chuàng)建它。
2)如果失敗,再嘗試 Microsoft.XMLHTTP 對象。
3、如果依然沒有建立 xmlHttp,則以非 Microsoft 的方式創(chuàng)建該對象。
*/
function createXmlHttp(){
var xmlHttp = false;
try {
//在 Microsoft 閱讀器上創(chuàng)建 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 閱讀器上創(chuàng)建 XMLHttpRequest 對象
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
/*發(fā)出要求:
在所有 Ajax 利用程序中基本都雷同的流程:
1、從 Web 表單中獲得需要的數(shù)據(jù)。
2、建立要連接的 URL。
3、打開到http://www.jyygyx.com/server/的連接。
4、設(shè)置http://www.jyygyx.com/server/在完成后要運行的函數(shù)。
5、發(fā)送要求。
*/
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 屬性可以告知http://www.jyygyx.com/server/在運行完成后做甚么。
由于代碼沒有等待http://www.jyygyx.com/server/,必須讓http://www.jyygyx.com/server/知道怎樣做以便您能作出響應(yīng)。
在這個示例中,如果http://www.jyygyx.com/server/處理完了要求,1個特殊的名為 updatePage() 的方法將被觸發(fā)。
需要特別注意的是該屬性在代碼中設(shè)置的位置 ―― 它是在調(diào)用 send() 之前 設(shè)置的。
發(fā)送要求之前必須設(shè)置該屬性,這樣http://www.jyygyx.com/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);
}
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈