jQuery學習筆記(3)之Ajax下
阿新 • • 發佈:2019-01-07
二. 請求伺服器資料
前面介紹的是如何在HTML頁面中載入非同步資料的方法,即如何從伺服器上取得靜態的資料。但頁面的應用遠不僅侷限於此,Ajax技術最終體現在與伺服器的動態資料實現人機互動中,即客戶端傳遞帶有引數的請求,伺服器接收後,分析所傳遞來的請求,並做出相應的響應,傳送對應資料至客戶端,客戶端接收請求返回的資料,從而實現了資料的雙向傳遞。
1. jQuery中的get( )方法
上一遍中通過呼叫全域性函式 $.get(),實現了XML文件的載入。除載入資料外, $.get()函式還可以實現資料的請求。
下面舉例說明:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>getScript函式獲取資料</title>
<style type="text/css">
body {font-size:13px}
.divFrame{width:260px;border:solid 1px #666}
.divFrame .divTitle{padding:5px;background-color:#eee;height:23px}
.divFrame .divTitle span{float:left;padding:2px}
.divFrame .divContent{padding:8px}
.divFrame .divContent .clsShow{font-size :14px}
.txt{border:#666 1px solid;padding:2px;width:118px;float:left;margin-right:3px}
.btn {border:#666 1px solid;padding:2px;width:80px;float:left;
filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr=#ffffff, EndColorStr=#ECE9D8);}
</style>
<script src="js/jquery-1.11.3.js"></script>
</head>
<body>
<div class="divFrame">
<div class="divTitle">
<span>姓名:</span>
<input id="txtName" type="text" class="txt" />
<input id="Button1" type="button"
class="btn" value="請求資料" />
</div>
<div class="divContent">
<div id="divTip"></div>
</div>
</div>
<script type="text/javascript">
$(function() {
$("#Button1").click(function() { //按鈕單擊事件
//開啟檔案,並通過回撥函式返回伺服器響應後的資料
$.get("UserInfo.aspx",
{ name: encodeURI($("#txtName").val()) },
function(data) {
$("#divTip")
.empty() //先清空標記中的內容
.html(data); //顯示伺服器返回的資料
})
})
})
</script>
</body>
</html>
UserInfo.aspx檔案中
<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %>
<%
string strName = System.Web.HttpUtility.UrlDecode(Request["name"]);//解碼姓名字元
string strHTML = "<div class='clsShow'>"; //初始化儲存內容變數
if (strName == "緣滅")
{
strHTML += "姓名:緣滅<br>";
strHTML += "性別:男<br>";
strHTML += "郵箱:[email protected]<hr>";
}
else if (strName == "李xx")
{
strHTML += "姓名:李xx<br>";
strHTML += "性別:女<br>";
strHTML += "郵箱:[email protected]<hr>";
}
strHTML += "</div>";
Response.Write(strHTML);
%>
注意:客戶端向伺服器傳遞引數時,使用的格式是
{key0:value0,key1:value1,…},
"key0"為引數名稱,"value0"為引數的值。如果引數的值是中文格式,必須通過使用encodeURI() 進行轉碼,當然,在客戶端接收時,使用decodeURI()進行解碼即可。
2. jQuery中的post( )方法
$.post(),也是帶引數向伺服器發出資料請求,本質上與 $.get()沒有太大的區別。所不同的是get方式不適合傳遞資料量較大的資料,同時,其請求的歷史資訊會儲存在瀏覽器的快取中,有一定的安全風險。而以post方式則不存在這兩個方面的不足。
3. jQuery中的$.ajax()方法
在jQuery中,$.ajax()是最底層的方法,也是功能最強的方法。其呼叫的語法格式為:
$.ajax( [options] )
其中可選項引數[options]為$.ajax()方法中的請求設定,其格式為key/value,既包含傳送請求的引數,也含有伺服器響應後回撥的資料,其部分名稱如下表所示:
引數名 | 型別 | 描述 |
---|---|---|
url | String | 傳送請求的地址 (預設為當前頁面) |
type | String | 資料請求方式 (post或get)預設為get |
data | String或Object | 傳送到伺服器的資料。如果不是字串則自動轉成字串格式,如果是get請求方式,那麼該字串將附在url的後面。 |
dataType | String | 伺服器返回的資料型別,如果沒有指定,jQuery將自動根據HTTP包MIME資訊自動判斷,伺服器返回的資料根據自動判斷的結果進行解析,傳遞給回撥函式,其可用型別為:html,script,text,xml,json。 |
success | Function | 請求成功後呼叫的回撥函式,該函式有兩個引數,一個是根據引數dataType處理後伺服器返回的資料,另一個是strStatus,用於描述狀態的字串。 |
error | Function | 請求失敗後呼叫的回撥函式,該函式有三個引數,第一個是XMLHttpRequest物件,第二個是出錯資訊strError,第三個是捕捉到的錯誤物件strObject。 |
下面舉例說明
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="js/jquery-1.11.3.js"></script>
<script src="js/template.js"></script>
<title>Document</title>
<style>
*{margin: 0;padding: 0;}
.clearfix:after{display: block;clear: both;content: "";visibility: hidden;height: 0;}
.clearfix{zoom:1;}
.fl{float: left;}
.fr{float: right;}
.touzi_free_list {height: 400px;overflow-y: auto;width: 330px;margin: 50px auto;border: 1px solid #eaeae2;}
.touzi_free_list ul li {border-bottom: 1px solid #eaeae2;overflow: hidden;clear: both;}
.touzi_free_list ul li a {display: block;padding: 16px 10px 12px;}
.touzi_free_list .audi_tt .audi_h3 {font-size: 14px;color: #333333;font-weight: normal;line-height: 22px;margin-bottom: 5px;}
.touzi_free_list .audi_tt .audi_p {font-size: 12px;color: #666666;font-weight: bold;}
</style>
</head>
<body>
<div class="touzi_free_list">
<ul id="js_auditionBox"></ul>
</div>
<script id="js_tmpAuditionItem" type="text/html">
<li class="{[ if active ]} active {[/if]} audition_li clearfix" data-type="{[format]}" data-key="{[url]}">
<a href="/videoplay?id={[id]}&tid={[teacher_id]}" class="clearfix" data-id="{[id]}">
<div class="audi_tt fl">
<h3 class="audi_h3">{[updated_at]}</h3>
<p class="audi_p">講師:{[product_title]}</p>
</div>
</a>
</li>
</script>
<script>
$.ajax({
type: 'post',
url: 'http://mapi.ktkt.com/mall/v1/skulist',
dataType: 'json',
success: function (data) {
console.log(data.list);
var a = data.list;
var html = '';
for (var i = 0; i < a.length; i++) {
html += template('js_tmpAuditionItem', a[i]);
}
$('#js_auditionBox').append(html);
}
})
</script>
</body>
</html>