在纯 JavaScript 中使用 XMLHttpRequest()。
XMLHttpRequest 是一个 API,它提供了在客户端和服务器之间传输数据的客户端功能。
xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({"email":"tomb@raider.com","name":"LaraCroft"});
xhr.send(data);
使用 AJAX 调用(首选方式)
$.ajax({
url: "https://youknowit.com/api/",
type: "POST",
data: { apiKey: "23462", method: "POST", ip: "208.74.35.5" },
dataType: "json",
success: function (result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
注意:密切关注开发人员工具或 firebug XHR 调试过程是了解更多关于任何技术中的 api 调用的好方法。