Asp.Net+Jquery.Ajax詳解2-$.Load

來源:互聯網
上載者:User

目錄(已經更新的文章會有串連,從7月25日開始,每2到3天更新一篇):

Asp.Net+Jquery.Ajax詳解1-開篇(2012.07.25發)

Asp.Net+Jquery.Ajax詳解2-$.Load(2012.07.26發)

Asp.Net+Jquery.Ajax詳解3-$.get和$.post(2012.07.30發)

Asp.Net+Jquery.Ajax詳解4-$.getJSON(2012.07.31發)

Asp.Net+Jquery.Ajax詳解5-$.getScript(2012.08.04發)

Asp.Net+Jquery.Ajax詳解6-$.ajaxSetup(2012.08.06發)

Asp.Net+Jquery.Ajax詳解7-全域Ajax事件(2012.08.09發)

Asp.Net+Jquery.Ajax詳解8-核心$.ajax(2012.08.12發)

Asp.Net+Jquery.Ajax詳解9-serialize和serializeArray(2012.08.15發)

Asp.Net+Jquery.Ajax詳解10-JSON和XML+寫在最後(2012.08.20發,結束啦!)

 

 

上一篇我們主要談了什麼是ajax,以及它的原始實現方式,簡單介紹了Jquery。從這篇開始,我們將深入瞭解Jquery.ajax.從$.load開始。

 

jQuery.load( url [, data][, callback] )

url:請求網頁的URL地址

data(可選):發送至伺服器的key/value資料

callback(可選):請求完成時的回呼函數

 

load()方法提供了回呼函數(callback),該函數有三個參數:responseText,textStatus,XMLHttpRequest,分別代表請求返回的內容、請求狀態和XMLHttpRequest對象。

 

 $("#result").load("Data/GetServiceInfo.aspx",function(responseText,textStatus,XMLHttpRequest){

//responseText:請求返回的內容

//textStatus:請求狀態:success、error、notmodified、timeout

//XMLHttpRequest:XMLHttpRequest對象

});

 

如果只需要載入GetServiceInfo.aspx頁面內的某些元素,那麼可以使用load()方法的URL參數來達到目的。通過為URL參數指定選擇符,可以很方便地從載入過來的HTML文檔裡篩選出所需要的內容。

load()方法的URL參數的文法結構為:“url selector”。注意,URL和選取器之間有一個空格。

 

 //測試load,使用選取器,過濾掉天津

        function LoadFilter(event) {

            $("#result").load("data/GetCity.aspx?resultType=html&t=" + (new Date()).getTime() + " ul>li:not(:contains('天津'))");

        }    

 

load()方法的傳遞方式根據參數data來自動指定。如果沒有參數傳遞,則採用GET方式傳遞;反之,則自動轉換為POST方式。

 

 //測試load,以Post方式請求,注意:預設使用 GET 方式 - 傳遞附加參數時自動轉換為 POST 方式

        function LoadPost(event) {

            $("#result").load("Data/GetServiceInfo.aspx", { "param": "TestLoad-Post" });

        }

 

注意:1、在load()方法中,無論Ajax請求是否成功,只要當請求完成(complete)後,回呼函數(callback)就被觸發

2、如果有參數,則在GetServiceInfo.aspx頁面接收參數時,應該用HttpContext.Current.Request["param"]形式,Request.Querysting擷取不到。

 

執行個體(vs2010):

用戶端—GetServiceInfo.aspx—

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JqueryAjaxLoad.aspx.cs"    Inherits="JqueryAjaxTest.JqueryAjaxLoad" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title>Jquery Ajax Test</title>    <%--引入Jquery庫--%>    <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>    <script type="text/javascript">        $(function () {            //為各個按鈕綁定事件            $("#TestLoad-Get").bind("click", LoadGet);            $("#TestLoad-Post").bind("click", LoadPost);            $("#TestLoad-Callback").bind("click", LoadCallback);            $("#TestLoad-Filter").bind("click", LoadFilter);        } );        //測試load,以Get方式請求        //加時間戳記(new Date()).getTime(),防止返回緩衝內容         function LoadGet(event) {            $("#result").load("Data/GetServiceInfo.aspx?param=TestLoad-Get&t=" + (new Date()).getTime());        }        //測試load,以Post方式請求,注意:預設使用 GET 方式 - 傳遞附加參數時自動轉換為 POST 方式        function LoadPost(event) {            $("#result").load("Data/GetServiceInfo.aspx", { "param": "TestLoad-Post" });        }        //測試load,使用回呼函數        //注意:load()方法提供了回呼函數(callback),該函數有三個參數,分別代表請求返回的內容、請求狀態和XMLHttpRequest對象        function LoadCallback(event) {            $("#result").load("Data/GetServiceInfo.aspx", { "param": "TestLoad-Callback" }, function (responseText, textStatus, XMLHttpRequest) {                $("#result").html("回呼函數在起作用,結果:" + responseText);                    });        }        //測試load,使用選取器        function LoadFilter(event) {            $("#result").load("data/GetCity.aspx?resultType=html&t=" + (new Date()).getTime() + " ul>li:not(:contains('天津'))");        }                     </script></head><body>    <form id="form1" runat="server">    <div>        <input id="TestLoad-Get" type="button" value="Load-Get方式" />        <input id="TestLoad-Post" type="button" value="Load-Post方式" />        <input id="TestLoad-Callback" type="button" value="Load-回呼函數" />        <input id="TestLoad-Filter" type="button" value="Load-過濾結果" />                   <div id="result">        </div>    </div>    </form></body></html>

服務端1—GetCity.aspx—

 

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace JqueryAjaxTest.Data{    public partial class GetMethodInfo : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            string param = "";            //擷取參數            if (!String.IsNullOrEmpty(HttpContext.Current.Request["param"]))            {                param = HttpContext.Current.Request["param"];            }                        //清空緩衝區            Response.Clear();            //將字串寫入響應輸出資料流            Response.Write("Http請求的方式為:"+Request.HttpMethod.ToUpper()+"; 傳遞過來的參數為:"+param);            //將當前所有緩衝的輸出發送的用戶端,並停止該頁執行            Response.End();        }    }}

服務端2——

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace JqueryAjaxTest.Data{    public partial class GetCity : System.Web.UI.Page    {        private string resultType = "json";        protected void Page_Load(object sender, EventArgs e)        {            //擷取請求的參數            if (!String.IsNullOrEmpty(Request.QueryString["resultType"])) {                resultType = Request.QueryString["resultType"].ToLower()=="html" ? "html" : "json";            }           string  html = GetResult(resultType);           //清空緩衝區           Response.Clear();           //將字串寫入響應輸出資料流           Response.Write(html);           //將當前所有緩衝的輸出發送的用戶端,並停止該頁執行           Response.End();        }        private string GetResult(string resultType) {            string result = "";            if (resultType == "html") {               //返回的html                result = @"<ul><li id=""1"">北京</li><li id=""2"">天津</li></ul>";            }            else if (resultType == "json") {                //返回的json資料                result = @"[{""pkid"":""0001"",""ProvinceId"":""BJ"",""CityName"":""北京"",""CityNameEn"":""Beijing"",""PostCode"":""010"",""isHotCity"":false}, {""pkid"":""0002"",""ProvinceId"":""TJ"",""CityName"":""天津"",""CityNameEn"":""Tianjin"",""PostCode"":""022"",""isHotCity"":false}]";                              }            return result;        }    }}

 第二篇到了,對比第一篇中的ajax原始方法,這次的方法明顯簡潔了許多。第三篇馬上就會殺到。如果想這個系列的文章到底寫些什麼,請參見第一篇。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.