函數原型:$.post(url, params, callback)
url是提交的地址,eg: "sample.ashx"
params是參數,eg: { name:"xxx" , id:"001" }
callback是回呼函數,eg: function(msg){ alert(msg); }
注意1:在sample.ashx那段,使用context.Request["id"]和context.Request["name"]來分別獲得值"001"和值"xxx",而不是使用context.Request.QueryString["id"]
注意2:這裡的callback裡的函數是在伺服器傳回值後被觸發,所以不需要另行判斷xmlHttp.readyState==4 && xmlHttp.status==200
接下來,我們來用一段代碼比較一下$.post方式和原始的xmlHttp方式
為了更好的對應,我讓2個方式實現一樣的功能,傳的值和回呼函數的名字一樣
/* xmlHttp方式 */
var xmlHttp; //定義對象xmlHttp
function createXMLHttpRequest() //建立xmlHttpRequest的函數
{
if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject( "Microsoft.XMLHTTP" );
}
else if(window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
}
function btn_onclick() //假設一個button點了以後觸發這個ajax
{
createXMLHttpRequest();
var url="sample.ashx?id=1&name=a"; //這裡假設傳給sample.ashx,傳2個值,id=1和name=a
xmlHttp.open( "POST" ,url,true);
xmlHttp.onreadystatechange=Response; //回呼函數是Response()
xmlHttp.send(null);
}
function Response()
{
if( xmlHttp.readyState==4 && xmlHttp.status==200 )
{
alert( xmlHttp.responseText ); //彈出一個框顯示伺服器返回的內容
}
}
/* $.post方式 */
function btn_onclick() //同樣還是這個事件和函數,還是點了以後觸發
{
/*
同樣還是sample.ashx,同樣是id=1&name=a
這裡的function(msg)是回調的函數,你可以把執行的內容直接寫在{}裡,msg表示伺服器返回的資料。
為了和上面的方式更好的對應起來,我這裡依然讓他調用Response,但是需要增加參數msg
*/
$.post("sample.ashx",{ id:"1",name:"a" }, function(msg){ Response(msg); });
}
function Response(msg)
{
alert( msg ); //彈出一個框顯示伺服器返回的內容
}