如何使用JavaScript进行AJAX调用,而不使用jQuery?
如何使用JavaScript进行AJAX调用,而不使用jQuery?
使用“原生”(纯)JavaScript:
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
}
使用jQuery:
$.ajax({
url: "test.html",
context: document.body,
success: function() {
$(this).addClass("done");
}
});
使用以下代码片段,您可以轻松地执行类似的操作,如下所示:
ajax.get('/test.php', {foo: 'bar'}, function() {});
这是代码片段:
var ajax = {};
ajax.x = function () {
if (typeof XMLHttpRequest !== 'undefined') {
return new XMLHttpRequest();
}
var versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
var xhr;
for (var i = 0; i < versions.length; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
} catch (e) {
}
}
return xhr;
};
ajax.send = function (url, callback, method, data, async) {
if (async === undefined) {
async = true;
}
var x = ajax.x();
x.open(method, url, async);
x.onreadystatechange = function () {
if (x.readyState == 4) {
callback(x.responseText)
}
};
if (method == 'POST') {
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
x.send(data)
};
ajax.get = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};
ajax.post = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, callback, 'POST', query.join('&'), async)
};
return x.responseText;
--然后返回每个ajax.send
调用。 - Samquery.join('&').replace(/%20/g, '+')
,对吧? - afsantos现在在现代浏览器中原生支持一个更好的Fetch API。fetch()
方法允许你发起网络请求。
例如,要从/get-data
请求一些JSON数据:
let options = {
method: 'GET',
headers: {}
};
fetch('/get-data', options)
.then(response => response.json())
.then(body => {
// Do something with body
});
async
和await
语法,请执行以下操作:async function doApi(url) {
const response = await fetch(url);
if( response.ok ) {
if( 200 <= response.status && response.status <= 299 ) {
const result = await response.json();
// do something awesome with result
} else {
console.log( `got a ${response.status}` );
}
}
}
<script src="https://cdn.rawgit.com/github/fetch/master/fetch.js"></script>
,就可以像专家一样使用fetch。 - TylerY86您可以使用以下函数:
function callAjax(url, callback){
var xmlhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
你可以在以下链接中尝试类似的解决方案:
GET
,所以您可以将它们添加到请求中,但为了更通用,我同意您的想法,我真的考虑更新答案,接受请求参数作为函数的参数,并传递方法(GET
或POST
),但阻止我的是我希望在这里保持答案尽可能简单,让人们尽快尝试它。实际上,我讨厌其他答案太长了,因为他们试图变得完美 :) - AbdelHadyxhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
这个版本使用纯 ES6/ES2015,怎么样?
function get(url) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('GET', url);
req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
req.onerror = (e) => reject(Error(`Network Error: ${e}`));
req.send();
});
}
get('foo.txt')
.then((data) => {
// Do stuff with data, if foo.txt was successfully loaded.
})
.catch((err) => {
// Do stuff on error...
});
JSON.parse()
将加载的数据转换成JS对象。req.responseType='json'
,但是很遗憾它没有IE支持, 所以我建议使用JSON.parse()
。XMLHttpRequest
,您可以异步尝试加载文件。这意味着您的代码执行将继续进行,而您的文件将在后台加载。为了在脚本中使用文件的内容,您需要一种机制来告诉您的脚本何时完成加载或加载失败。这就是 promises 发挥作用的地方。还有其他解决此问题的方法,但我认为 promises 最方便。 - Rotareti简单的GET请求
httpRequest = new XMLHttpRequest()
httpRequest.open('GET', 'http://www.example.org/some.file')
httpRequest.send()
简单的POST请求
httpRequest = new XMLHttpRequest()
httpRequest.open('POST', 'http://www.example.org/some/endpoint')
httpRequest.send('some data')
我们可以使用可选的第三个参数来指定请求应该是异步(true, 默认值)还是同步(false)。
// Make a synchronous GET request
httpRequest.open('GET', 'http://www.example.org/some.file', false)
在调用httpRequest.send()
之前,我们可以设置请求头信息。
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
我们可以通过在调用httpRequest.send()
之前将httpRequest.onreadystatechange
设置为一个函数来处理响应。httpRequest.onreadystatechange = function(){
// Process the server response here.
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
您可以根据浏览器获取正确的对象,使用
function getXmlDoc() {
var xmlDoc;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlDoc = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlDoc;
}
通过正确的对象,GET 可以被抽象为:
function myGet(url, callback) {
var xmlDoc = getXmlDoc();
xmlDoc.open('GET', url, true);
xmlDoc.onreadystatechange = function() {
if (xmlDoc.readyState === 4 && xmlDoc.status === 200) {
callback(xmlDoc);
}
}
xmlDoc.send();
}
向以下地址进行POST请求:
function myPost(url, data, callback) {
var xmlDoc = getXmlDoc();
xmlDoc.open('POST', url, true);
xmlDoc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlDoc.onreadystatechange = function() {
if (xmlDoc.readyState === 4 && xmlDoc.status === 200) {
callback(xmlDoc);
}
}
xmlDoc.send(data);
}
我想找一种方法,通过ajax使用promises而不使用jQuery。在HTML5 Rocks上有一篇文章讲解ES6 promises。(你可以使用像Q这样的promise库来进行polyfill)。你可以使用我从文章中复制的代码片段。
function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
注意:我还写了一篇关于此内容的 文章。
您可以使用XMLHttpRequest()
构造函数创建一个新的XMLHttpRequest
(XHR)对象,该对象将允许您使用标准HTTP请求方法(例如GET
和POST
)与服务器进行交互:
const data = JSON.stringify({
example_1: 123,
example_2: 'Hello, world!',
});
const request = new XMLHttpRequest();
request.addEventListener('load', function () {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
});
request.open('POST', 'example.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
你也可以使用fetch()
方法获取一个Promise
,该Promise解析为代表响应的Response
对象:
const data = JSON.stringify({
example_1: 123,
example_2: 'Hello, world!',
});
fetch('example.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: data,
}).then(response => {
if (response.ok) {
response.text().then(response => {
console.log(response);
});
}
});
POST
数据并且不需要来自服务器的响应,则最简短的解决方法是使用 navigator.sendBeacon()
:const data = JSON.stringify({
example_1: 123,
example_2: 'Hello, world!',
});
navigator.sendBeacon('example.php', data);