当前位置: 移动技术网 > IT编程>开发语言>.net > Asp.Net+Jquery.Ajax详解2-$.Load

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

2018年04月14日  | 移动技术网IT编程  | 我要评论

古巴比伦驭王记,风流医圣,可口可乐小子影评

 


 

上一篇我们主要谈了什么是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—

 

[html]
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JqueryAjaxLoad.aspx.cs" 
    Inherits="JqueryAjaxTest.JqueryAjaxLoad" %> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="https://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"> 
    <p> 
        <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-过滤结果" /> 
            
        <p id="result"> 
        </p> 
    </p> 
    </form> 
</body> 
</html> 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JqueryAjaxLoad.aspx.cs"
    Inherits="JqueryAjaxTest.JqueryAjaxLoad" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://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">
    <p>
        <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-过滤结果" />
          
        <p id="result">
        </p>
    </p>
    </form>
</body>
</html>

服务端1—GetCity.aspx—

 

[csharp]
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(); 
 
        } 
    } 

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——

[csharp] 
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; 
        } 
    } 

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;
        }
    }
}
作者:shan9liang
 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网