http的交互方法有四種:get、post、put(增長數據)、delete(刪除數據)javascript
jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)
jQuery.get(url,data,success(response,status,xhr),dataType)
url(必需,其餘爲可選):要發送的url
data:數據
success:成功時的操做
success(data, textStatus, jqXHR):(處理後的數據、請求狀態字符串、jq1.4中xhr對象)
dataType:響應的數據類型
實例:
var loginFn=function(){ $.ajax({ type:'post', //String 默認爲GET timeout:'2000', //Number 設置超時時間(毫秒) url:{"url"}, //String 發送請求的地址 dataType:"json", //String xml、html、script、json、jsonp、jQuery、text data:{'ur;':url}, //或者data能夠如如下寫法 data:{username:$("#username").val(),content:$("#content").val()}, //GET請求中將附在URL後;對象必須爲key/value形式。若是是數組,jQuery將自動爲不一樣值對應同一名稱例如:{foo:["bar1","bar2"]}轉換爲&foo=bar1&foo=bar2 //提交前回調函數(發送請求前能夠修改XMLHttpRequest對象的函數) beforeSend:function(XMLHttpRequest){ this; //調用本次Ajax請求時傳遞的options參數 }, //請求成功後處理(data多是xmlDoc、jsonObj、html、text;textStatus (請求狀態):success、error、notimodified、timeout) success:function(data,textStatus){ this; //調用本次Ajax請求時傳遞的options參數//window.location.href = data.getCodeUrl;/*location.reload();*/ }, //請求失敗後處理(一般狀況下textStatus和errorThrown只有其中一個包含信息) error: function (XMLHttpRequest,textStatus,errorThrown) { this; //調用本次Ajax請求時傳遞的options參數 console.log("error-----------"); }, //請求完成後處理(請求成功或失敗時均調用) complete:function(XMLHttpRequest,textStatus){ this; //調用本次Ajax請求時傳遞的options參數 } }); }
$("#object").on("click",loginFn);
接上,success擴展:
success: function(xml){ $(xml).find('item').each(function(){ var item_text = $(this).text(); $('<li></li>') .html(item_text) .appendTo('ol'); }); }
load:請求加載數據並返回到指定位置。通常爲經常使用爲:點擊或輸入文本框在指定位置加載出文本,
若是提供數據的是方法,得用post或者get才能生效
實例:
$("button").click(function(){ $("div").load('demo_ajax_load.txt'); });
$("#result").load("ajax/test.html", function() { alert("Load was performed."); });
function() getXhr{ var xhr; if(window.XMLHttpRequest){ xhr=new XMLHttpRequest();//非ie瀏覽器 }else{ xhr=new ActiveXobject('Microsoft.XMLHttp');//ie瀏覽器 } }
/*保證返回內容包含text/html,超文本文件
* MIME(多功能網際郵件擴充協議)
* 被定義在Content-Type header中
*經常使用的有:
超文本標記語言文本 .html,.html text/html
普通文本 .txt text/plain
RTF文本 .rtf application/rtf
GIF圖形 .gif image/gif
* */
1 xhr.overrideMimeType('text/html');