Ajax load()方法,ajaxload方法

來源:互聯網
上載者:User

Ajax load()方法,ajaxload方法

《1》

load()函數用於從伺服器載入資料,並使用返回的html內容替換當前匹配元素的內容。

load()函數預設使用GET方式,如果提供了對象形式的資料,則自動轉為POST方式。
因為預設使用的是Get請求方式,所以我們也可以在url加資料進行提交。

例如$("#box").load("loadTest.html?name=zhang&age=25")


load()方法可以參數三個參數:

url(必須,請求html 檔案的url 地址,參數類型為String)
data(可選,發送的key/value 資料,參數類型為Object)
callback(可選,成功或失敗的回呼函數,參數類型為函數Function)


load()方法是局部方法,因為他需要一個包含元素的jQuery 對象作為首碼。例如$("#box").load()

而$.get()和$.post()是全域方法,無須指定某個元素。對於用途而言,.load()適合做靜態檔案的非同步擷取,
而對於需要傳遞參數到伺服器頁面的,$.get()和$.post()更加合適。


從另外一個頁面載入資料到當前頁

<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title>Ajax</title>    <script src="jquery-1.11.2.js"></script>    <style type="text/css">    </style></head><body>    <input type="button" id="loadData" value="非同步載入資料" />    <div id="box"></div></body></html><script type="text/javascript">       $(function () {        //----------------------如何從另外一個頁面載入資料到當前頁                $("#loadData").click(function(){            $("#box").load("loadTest.html"); //將locdTest.html頁面裡面的資料通過非同步形式載入到當前頁面中的#box元素中。        })                $("#loadData").click(function () {            $("#box").load("loadTest.html p"); //把locdTest.html頁面中的<p>標籤通過非同步形式載入到當前頁面中的#box元素中。        })               $("#loadData").click(function () {            $("#box").load("loadTest.html .para"); //把locdTest.html頁面中的class屬性值為para的標籤通過非同步形式載入到當前頁面中的#box元素中。        })                       $("#loadData").click(function () {            $("#box").load("loadTest.html #city"); //把locaTest.html頁面中id屬性值為city的標籤通過非同步形式載入到當前頁面中的#box元素中        })         $("#loadData").click(function () {            $("#box").load("loadTest.html #a p"); //把locaTest.html頁面中id屬性值為a的元素下面的<p>標籤通過非同步形式載入到當前頁面中的#box元素中        })    })</script>


如何從伺服器載入資料到當前頁請求頁代碼

<html><head>    <title>Ajax</title>    <script src="jquery-1.11.2.js"></script></head><body>       <label for="UserId">請輸入使用者的ID編號:</label><input type="text" id="UserId" name="UserId" style="width:20px" />    <input type="button" id="loadData" value="非同步載入資料" />    <div id="box"></div></body></html><script type="text/javascript">     $(function () {        //----------------------如何從伺服器載入資料到當前頁        $("#loadData").click(function () {            var userId = $("#UserId").val();            if (userId.length<=0) {                alert("請輸入您要尋找資料的編號!");                return;            }            //Get傳值方式            //$("#box").load("loadHandler.ashx?id=" + userId); //load()函數預設使用GET方式                        //Post傳值方式            //$("#box").load("loadHandler.ashx", { id: userId }); //load()函數預設使用GET方式,如果提供了對象形式的資料,則自動轉為POST方式。            //我們再來看看第三個參數回呼函數            $("#box").load("loadHandler.ashx", { id: userId }, function (data, status, jqXHR) {                alert(data); // data是請求成功後返回的資料                alert(status); //列印出:success   如果請求成功後返回的狀態值就是 success 如果請求失敗返回的狀態值是error                alert(jqXHR.status); //列印出:200    列印出當前請求的Http狀態代碼 例如:200,403,405,505等等。 200表示伺服器成功的返回了資料                alert(jqXHR.statusText); //列印出:OK                if (status == "success")                {                    $("#box").html(data + "哈哈"); //在請求成功後,我們還可以對資料進行一下處理。                                   }            })                    })    })</script>

伺服器代碼

using System;using System.Collections.Generic;using System.Configuration;using System.Data;using System.Data.SqlClient;using System.Linq;using System.Web;namespace jqueryTest{    /// <summary>    /// loadHandler 的摘要說明    /// </summary>    public class loadHandler : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/html";            string id = context.Request["id"];            string userInfo= GetByIdData(Convert.ToInt32(id));            if (userInfo == "")            {                context.Response.Write("你尋找的資料不存在");                return;            }            else            {                context.Response.Write(userInfo);            }        }        public string  GetByIdData(int id)        {            string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;            using (SqlConnection conn = new SqlConnection(connStr))            {                conn.Open();                using (SqlCommand cmd = conn.CreateCommand())                {                    cmd.CommandText = "select * from T_UserInfo where id=@id";                    SqlParameter sp = new SqlParameter("@id", id);                    cmd.Parameters.Add(sp);                    DataTable dt = new DataTable();                    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))                    {                        adapter.Fill(dt);                                            }                    if (dt.Rows.Count <= 0 || dt.Columns.Count <= 0)                    {                        return "";                    }                    string str=null;                    for (int i = 0; i < dt.Columns.Count; i++)                    {                        str += dt.Rows[0][i].ToString()+ " | "; //擷取第一行第i列的資料                                           }                    return str;   //返回第一行的所以資料                                    }            }        }        public bool IsReusable        {            get            {                return false;            }        }    }}

通過回呼函數處理過後的資料: 如






聯繫我們

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