$.get(url, [data], [callback], [type])
// 參數:url 必填,data 查詢參數對象,callback 成功回調,type 響應類型(xml/html/script/json/text)
$.get("/api/users", {page:1}, function(res){ console.log(res); }, "json");
$.post(url, [data], [callback], [type])
// 參數結構同 $.get,但數據作為請求體發送,無長度限制,較安全
$.post("/api/login", {user:"admin", pass:"123456"}, function(res){ alert(res.msg); }, "json");
| 特性 | GET | POST |
|---|---|---|
| 參數位置 | URL 查詢字符串 | HTTP 請求體 |
| 長度限制 | ~2KB | 理論無限制 |
| 緩存 | 瀏覽器會緩存 | 不緩存 |
| 安全性 | 參數可見歷史記錄 | 相對安全 |
| 服務端獲取 | query string | request body |
$.getScript("test.js"); // 載入後自動執行
$.getScript("jquery.color.js", function(){
$("#go").click(function(){ $(".block").animate({backgroundColor:'pink'},1000); });
});
$.getJSON("test.json", function(data){
$.each(data, function(i, comment){
$("#resText").append('
").attr("src", item.media.m).appendTo("#resText");
if(i==3) return false;
});
});
JSONP 原理:動態創建 <script> 標籤,服務端返回 callbackName(jsonData),繞過同源策略。
$.ajax({
url: "/api/data",
type: "POST",
data: {id:1},
dataType: "json",
timeout: 5000,
beforeSend: function(xhr){ xhr.setRequestHeader("X-Token", "abc"); },
success: function(res){ console.log(res); },
error: function(xhr, status, err){ console.error(status, err); },
complete: function(){ console.log("請求完成"); }
});
async:是否異步(默認 true)。cache:GET 請求是否緩存(默認 true,dataType script/jsonp 默認 false)。headers:自定義請求頭對象。xhrFields:設置 withCredentials: true 攜帶 Cookie 跨域。statusCode:針對特定 HTTP 碼註冊處理器。$.ajax 或封裝 request(options) 便於攔截器、錯誤統一處理。async: false(同步請求會阻塞 UI,已棄用)。timeout 避免長時間無響應。
'+comment.username+'
'+comment.content+'