asp.net中jQuery $post用法

來源:互聯網
上載者:User

函數原型:$.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 );       //彈出一個框顯示伺服器返回的內容
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.