Javascript 如何在没有 jQuery 的情况下进行 AJAX 调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8567114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make an AJAX call without jQuery?
提问by discky
How to make an AJAX call using JavaScript, without using jQuery?
如何使用 JavaScript 进行 AJAX 调用,而不使用 jQuery?
回答by dov.amir
With "vanilla" JavaScript:
使用“香草”JavaScript:
<script type="text/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();
}
</script>
With jQuery:
使用 jQuery:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
回答by Petah
Using the following snippet you can do similar things pretty easily, like this:
使用下面的代码片段,你可以很容易地做类似的事情,就像这样:
ajax.get('/test.php', {foo: 'bar'}, function() {});
Here is the snippet:
这是片段:
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)
};
回答by Will Munn
I know this is a fairly old question, but there is now a nicer API available natively in newer browsers. The fetch()
method allow you to make web requests.
For example, to request some json from /get-data
:
我知道这是一个相当古老的问题,但现在在较新的浏览器中提供了一个更好的 API 。该fetch()
方法允许您发出 Web 请求。例如,从/get-data
以下位置请求一些 json :
var opts = {
method: 'GET',
headers: {}
};
fetch('/get-data', opts).then(function (response) {
return response.json();
})
.then(function (body) {
//doSomething with body;
});
See herefor more details.
请参阅此处了解更多详情。
回答by AbdelHady
You can use the following function:
您可以使用以下功能:
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();
}
You can try similar solutions online on these links:
您可以通过以下链接在线尝试类似的解决方案:
回答by Rotareti
How about this version in plain ES6/ES2015?
这个版本在普通的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();
});
}
The function returns a promise. Here is an example on how to use the function and handle the promiseit returns:
该函数返回一个promise。下面是一个关于如何使用函数和处理它返回的承诺的例子:
get('foo.txt')
.then((data) => {
// Do stuff with data, if foo.txt was successfully loaded.
})
.catch((err) => {
// Do stuff on error...
});
If you need to load a json file you can use JSON.parse()
to convert the loaded data into an JS Object.
如果您需要加载一个 json 文件,您可以使用JSON.parse()
将加载的数据转换为 JS 对象。
You can also integrate req.responseType='json'
into the function but unfortunately there is no IE support for it, so I would stick with JSON.parse()
.
您也可以集成req.responseType='json'
到该功能中,但不幸的是没有 IE 支持它,所以我会坚持使用JSON.parse()
.
回答by Rafay
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "sumGet.phtml?figure1=5&figure2=10", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse); // Shows "15"
回答by HarlemSquirrel
Use XMLHttpRequest.
Simple GET request
简单的 GET 请求
httpRequest = new XMLHttpRequest()
httpRequest.open('GET', 'http://www.example.org/some.file')
httpRequest.send()
Simple POST request
简单的POST请求
httpRequest = new XMLHttpRequest()
httpRequest.open('POST', 'http://www.example.org/some/endpoint')
httpRequest.send('some data')
We can specify that the request should be asynchronous(true), the default, or synchronous(false) with an optional third argument.
我们可以使用可选的第三个参数指定请求应该是异步(真)、默认值或同步(假)。
// Make a synchronous GET request
httpRequest.open('GET', 'http://www.example.org/some.file', false)
We can set headers before calling httpRequest.send()
我们可以在调用之前设置标题 httpRequest.send()
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
We can handle the response by setting httpRequest.onreadystatechange
to a function before calling httpRequest.send()
我们可以通过httpRequest.onreadystatechange
在调用之前设置一个函数来处理响应httpRequest.send()
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.');
}
}
}
回答by brunops
You can get the correct object according to the browser with
您可以根据浏览器获取正确的对象
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;
}
With the correct object, a GET might can be abstracted to:
使用正确的对象,可以将 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();
}
And a POST to:
和一个 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);
}
回答by Aligned
I was looking for a way to include promises with ajax and exclude jQuery. There's an article on HTML5 Rocksthat talks about ES6 promises. (You could polyfill with a promise library like Q) You can use the code snippet that I copied from the article.
我一直在寻找一种方法来包含 ajax 的承诺并排除 jQuery。有一篇关于HTML5 Rocks的文章讨论了 ES6 承诺。(您可以使用像Q这样的承诺库进行 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();
});
}
Note: I also wrote an article about this.
注意:我也写了一篇关于这个的文章。
回答by Ryan
If you don't want to include JQuery, I'd try out some lightweight AJAX libraries.
如果您不想包含 JQuery,我会尝试一些轻量级的 AJAX 库。
My favorite is reqwest. It's only 3.4kb and very well built out: https://github.com/ded/Reqwest
我最喜欢的是reqwest。它只有 3.4kb 并且非常好构建:https: //github.com/ded/Reqwest
Here's a sample GET request with reqwest:
这是带有 reqwest 的示例 GET 请求:
reqwest({
url: url,
method: 'GET',
type: 'json',
success: onSuccess
});
Now if you want something even more lightweight, I'd try microAjax at a mere 0.4kb: https://code.google.com/p/microajax/
现在,如果您想要更轻量级的东西,我会尝试仅 0.4kb 的 microAjax:https: //code.google.com/p/microajax/
This is all the code right here:
这是这里的所有代码:
function microAjax(B,A){this.bindFunction=function(E,D){return function(){return E.apply(D,[D])}};this.stateChange=function(D){if(this.request.readyState==4){this.callbackFunction(this.request.responseText)}};this.getRequest=function(){if(window.ActiveXObject){return new ActiveXObject("Microsoft.XMLHTTP")}else{if(window.XMLHttpRequest){return new XMLHttpRequest()}}return false};this.postBody=(arguments[2]||"");this.callbackFunction=A;this.url=B;this.request=this.getRequest();if(this.request){var C=this.request;C.onreadystatechange=this.bindFunction(this.stateChange,this);if(this.postBody!==""){C.open("POST",B,true);C.setRequestHeader("X-Requested-With","XMLHttpRequest");C.setRequestHeader("Content-type","application/x-www-form-urlencoded");C.setRequestHeader("Connection","close")}else{C.open("GET",B,true)}C.send(this.postBody)}};
And here's a sample call:
这是一个示例调用:
microAjax(url, onSuccess);