AJAX請求 $.get方法的使用


使用jQuery的$.get方法可以以GET方式發起AJAX請求。$.get方法是jQuery的實用工具函數。

get方法語法

$.get(url,parameters,callback)

參數

 

url

(字符串)服務器端資源地址。

parameter

(對象)需要傳遞到服務器端的參數。其形式為“鍵/值”。它會查詢的字符串追加到url。

callback

(函數)在請求完成時被調用。該函數參數依次為響應體和狀態。

返回值

XHR實例

看個簡單的例子

客戶端代碼:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function () {
  $('#selectNum').change(function () {
    var num = $(this).val();
    $.get('Server.aspx', { id: num }, function (text,status) { alert(text); });
  })
})
</script>
</head>
<body>
<select id="selectNum">
  <option value="0">--select--</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
</body>
</html>

服務端主要代碼:

protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    if (Request["id"] != null && !string.IsNullOrEmpty(Request["id"].ToString()))
    {
      Response.Write(GetData(Request["id"].ToString()));
    }
  }
}

protected string GetData(string id)
{
  string str = string.Empty;
  switch (id)
  {
    case "1":
      str += "This is Number 1";
      break;
    case "2":
      str += "This is Number 2";
      break;
    case "3":
      str += "This is Number 3";
      break;
    default:
      str += "Warning Other Number!";
      break;
  }
  return str;
}

運行程序,結果如圖:

clip_image001

用httpwatcher攔截請求信息,當下拉框中選擇數字時,可以截取到如下請求信息。

使用$.get方法時的截圖:

clip_image003

從圖中我們可以看到,參數id被追加到了url地址后面。

$.get方法發起的是GET請求,這種請求大多用於查詢某些信息。

Demo下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM