天天看點

ajax xmlhttp屬性,AJAX XMLHttpRequest對象詳解

AJAX是一種建立互動式網頁應用的網頁開發技術,是異步Javascript和XML的集合。其核心是XMLHttpRequest對象,可以在不向伺服器端送出整個頁面的情況下,實作局部更新網頁,它是AJAX的Web應用程式架構的一項關鍵技術。

基本屬性:

ajax xmlhttp屬性,AJAX XMLHttpRequest對象詳解

基本方法:

ajax xmlhttp屬性,AJAX XMLHttpRequest對象詳解

XMLHttpRequest五步法:

第一:建立XMLHttpRequest對象

第二:注冊回調函數

第三:設定和伺服器互動的參數

第四:設定向伺服器端發送的資料,啟動和伺服器端的互動

第五:判斷和伺服器端的互動是否完成,還有判斷伺服器端是否傳回正确的資料

HTML代碼:

var xmlhttp;

function submit() {

//1、建立XMLHttpRequest對象

if (window.XMLHttpRequest) {

xmlhttp = new XMLHttpRequest();

if (xmlhttp.overrideMineType) {//針對某些特定版本的mozillar浏覽器的BUG進行修正

//将覆寫發送給伺服器的頭部,強制 text/xml 作為 mime-type

xmlhttp.overrideMineType("text/xml");

}

} else if (window.ActiveXObject) {//針對IE浏覽器進行處理

var activexName = ["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0",

"MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0",

"MSXML2.XMLHTTP", "Miscrosoft XMLHTTP"];

for (var i = 0; i < activexName.length; i++) {

try{

xmlhttp=new ActiveXObject(activexName[i]);

break;

} catch (e) { }

}

}

if (xmlhttp == undefined || xmlhttp == null) {

alert("目前浏覽器不支援插件XMLHttpRequest對象,請更換浏覽器");

return;

}

//2、注冊回調函數

xmlhttp.onreadystatechange = callback;

//擷取目前值

var username = document.getElementById("userName").value;

//設定字元串參數,并進行編碼(用于POST送出方式)

var args = "username=" + encodeURIComponent(username);

//GET 互動

//3、設定和伺服器端互動的參數

//xmlhttp.open("GET", "XMLHttpRequest.aspx?username=" + username, true);

//POST互動

//3、設定和伺服器端互動的參數

//使用Post方式不用擔心緩存

xmlhttp.open("POST", "XMLHttpRequest.aspx?username=" + username, true);

//設定Content-Type類型,告知伺服器實體中有參數

xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

//4、設定向伺服器端發送的資料,啟動和伺服器端的互動

//用于GET送出

//xmlhttp.send(null);

//用于POST送出

xmlhttp.send(args);

function callback() {

//5、判斷和伺服器端的互動是否完成,還有判斷伺服器端是否正确傳回了資料

if (xmlhttp.readyState == 4) {//readyState=4表示互動完成

if (xmlhttp.status == 200) {//status=200表示正确傳回了資料

//純文字資料的接收方法

var message = xmlhttp.responseText;

var div = document.getElementById("message");

div.innerHTML = message;

}

}

}

}

aspx中的代碼:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace XMLHttpRequest五步法

{

public partial class XMLHttpRequest : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

//Response.Clear();

//擷取目前值,get送出使用Request.QueryString方法

//string username = Request.QueryString["username"];

//POST送出,使用Request.Form

string username = Request.Form["username"];

Response.Write("姓名:'"

+ username + "'

時間:'" + DateTime.Now.ToString() + "'");

Response.End();

}

}

}

總結:

XMLHttpRequest是AJAX的核心部分,需要好好了解。剛開始接觸的時候,有些不明白是怎麼回事,而且視訊中講的也是原生的AJAX,表面上看來不太好了解,但是通過具體的demo實踐,就會發現其實這個挺容易了解的。

以上就是本文的全部内容,希望對大家的學習有所幫助。