原生及jq方式使用ajax
1.原生js實現(xiàn)Ajax方法:
var Ajax={get: function (url,fn){var obj=new XMLHttpRequest(); // XMLHttpRequest對象用于在后臺與服務(wù)器交換數(shù)據(jù) obj.open('GET',url,true); obj.onreadystatechange=function(){ if (obj.readyState == 4 && obj.status == 200 || obj.status == 304) { // readyState==4說明請求已完成 fn.call(this, obj.responseText); //從服務(wù)器獲得數(shù)據(jù) } }; obj.send(null); }, post: function (url, data, fn) { var obj = new XMLHttpRequest(); obj.open("POST", url, true); obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // 發(fā)送信息至服務(wù)器時內(nèi)容編碼類型 obj.onreadystatechange = function () { if (obj.readyState == 4 && (obj.status == 200 || obj.status == 304)) { // 304未修改 fn.call(this, obj.responseText); } }; obj.send(data); } }注釋:
a.open() 方法需要三個參數(shù):
第一個參數(shù)定義發(fā)送請求所使用的方法(GET 還是 POST)。與 POST 相比,GET 更簡單也更快,并且在大部分情況下都能用。然而,在以下情況中,請使用 POST 請求:
- 無法使用緩存文件(更新服務(wù)器上的文件或數(shù)據(jù)庫)
- 向服務(wù)器發(fā)送大量數(shù)據(jù)(POST 沒有數(shù)據(jù)量限制)
- 發(fā)送包含未知字符的用戶輸入時,POST 比 GET 更穩(wěn)定也更可靠
第二個參數(shù)規(guī)定服務(wù)器端腳本的 URL(該文件可以是任何類型的文件,比如 .txt 和 .xml,或者服務(wù)器腳本文件,比如 .asp 和 .php (在傳回響應(yīng)之前,能夠在服務(wù)器上執(zhí)行任務(wù)))。
第三個參數(shù)規(guī)定應(yīng)當對請求進行異步地處理(true(異步)或 false(同步))。
b.send() 方法可將請求送往服務(wù)器。
c.onreadystatechange 屬性存有處理服務(wù)器響應(yīng)的函數(shù)。
d.readyState 屬性存有服務(wù)器響應(yīng)的狀態(tài)信息。每當 readyState 改變時,onreadystatechange 函數(shù)就會被執(zhí)行。
2.jq方式實現(xiàn)Ajax方法:
$(document).ready(function(){ $("#search").click(function(){ $.ajax({ type: "GET", url: "http://127.0.0.1:8080/ajaxdemo/serverjson2.php?number=" + $("#keyword").val(), dataType: "json", success: function(data) { if (data.success) { $("#searchResult").html(data.msg); } else { $("#searchResult").html("出現(xiàn)錯誤:" + data.msg); } }, error: function(jqXHR){ alert("發(fā)生錯誤:" + jqXHR.status); }, }); }); $("#save").click(function(){ $.ajax({ type: "POST", url: "serverjson.php", data: { name: $("#staffName").val(), number: $("#staffNumber").val(), sex: $("#staffSex").val(), job: $("#staffJob").val() }, dataType: "json", success: function(data){ if (data.success) { $("#createResult").html(data.msg); } else { $("#createResult").html("出現(xiàn)錯誤:" + data.msg); } }, error: function(jqXHR){ alert("發(fā)生錯誤:" + jqXHR.status); }, }); }); });注:
type:類型,“POST”或者“GET”,默認為“GET”
url:發(fā)送請求的地址
data:是一個對象連同請求發(fā)送到服務(wù)器的數(shù)據(jù)
dataType:預(yù)期服務(wù)器返回的數(shù)據(jù)類型。如果不指定,jQuery將自動根據(jù)包含HTTP包MIME信息來智能判斷,一般我們采用json格式,可以設(shè)置為“json”
success:是一個方法,請求成功后的回掉函數(shù)。傳入返回后的數(shù)據(jù),以及包含成功代碼的字符串
error:是一個方法,請求失敗時調(diào)用此函數(shù)。傳入XMLHttpRequest對象
轉(zhuǎn)載于:https://www.cnblogs.com/rushjs/p/7094621.html
總結(jié)
以上是生活随笔為你收集整理的原生及jq方式使用ajax的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VueJS定义组件规则
- 下一篇: 【k8s】K8S中的IP地址(Node