AJAX請求 $.ajaxSetup方法的使用


使用jQuery的$.ajaxSetup方法可以設置AJAX請求的默認參數選項,當程序中需要發起多個AJAX請求時,則不用再為每一個請求配置請求的參數。

$.ajaxSetup方法語法

$.ajaxSetup(properties)

參數

 

properties

(對象)對象實例,其屬性定義一組默認的AJAX屬性。這些屬性與前面講述的$.ajax函數屬性相同。

返回值

未定義

需要注意的是用$.ajaxSetup函數所設置的默認值不會應用到load()命令上。對於實用工具函數,如$.get()和$.post(),其HTTP方法不會因為使用這些默認值而被覆蓋。設置GET的默認類型不會導致$.post()使用HTTP的GET方法。

看個例子

客戶端代碼:

<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 () {
  var show = $('#show');
  $('#selectNum').change(function () {
    var idValue = $(this).val();
    $.get('Server.aspx', { id: idValue }, function (data) { show.append(data+'<br/>'); });
  });

  $.ajaxSetup({
    timeout: 3000,
    dataType: 'html',
    //請求成功后觸發
    success: function (data) { show.append('success invoke!' + data + '<br/>'); },
    //請求失敗遇到異常觸發
    error: function (xhr, status, e) { show.append('error invoke! status:' + status+'<br/>'); },
    //完成請求后觸發。即在success或error觸發后觸發
    complete: function (xhr, status) { show.append('complete invoke! status:' + status+'<br/>'); },
    //發送請求前觸發
    beforeSend: function (xhr) {
    //可以設置自定義標頭
    xhr.setRequestHeader('Content-Type', 'application/xml;charset=utf-8');
    show.append('beforeSend invoke!' +'<br/>');
    },
  })
})
</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>
<div id="show">
</div>
</body>
</html>

服務端主要代碼:

protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    if (Request["id"] != null && !string.IsNullOrEmpty(Request["id"].ToString()))
    {
      //啟用下面一行代碼則會使ajax請求超時
      // System.Threading.Thread.Sleep(4000);
      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_image002

Demo下載


免責聲明!

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



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