如何在没有jQuery的情况下进行AJAX调用?
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"
这项工作将跨浏览器? – Benubird 2013-04-26 16:55:50
不要做同步呼叫。使用xhReq.onload并使用回调。 – 2013-05-05 20:52:11
@kenansulayman你能举例说明你的意思吗? – 2013-10-26 22:29:28
以 “香草” 的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>
使用jQuery:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
请停止支持IE5/IE6 – Archibald 2013-08-14 13:23:52
@DrewNoakes:它绝对更具可读性,但不幸的是,当我在Opera Mini浏览器上尝试它时,它不被支持,所以我猜 它的支持不太普及 – BornToCode 2014-05-18 21:09:56
@Fractaliste如果你只是在与xmlhttp.status有关的if块之后调用回调,然后在那里给他们打电话,你就完成了。 – Jay 2015-06-18 20:30:52
<html>
<script>
var xmlDoc = null ;
function load() {
if (typeof window.ActiveXObject != 'undefined') {
xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
xmlDoc.onreadystatechange = process ;
}
else {
xmlDoc = new XMLHttpRequest();
xmlDoc.onload = process ;
}
xmlDoc.open("GET", "background.html", true);
xmlDoc.send(null);
}
function process() {
if (xmlDoc.readyState != 4) return ;
document.getElementById("output").value = xmlDoc.responseText ;
}
function empty() {
document.getElementById("output").value = '<empty>' ;
}
</script>
<body>
<textarea id="output" cols='70' rows='40'><empty></textarea>
<br></br>
<button onclick="load()">Load</button>
<button onclick="empty()">Clear</button>
</body>
</html>
HTML:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","1.php?id=99freebies.blogspot.com",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
PHP:
<?php
$id = $_GET[id];
print "$id";
?>
单行ifs不需要大括号,没有人使用IE6,这可能是复制粘贴,使用onload而不是onreadystatechange,为可能的递归调用捕获错误,xmlhttp是一个可怕的变量名称,只是称它为x。 – super 2015-12-21 10:00:16
使用下面的代码片段,你可以很轻松地做类似的事情,就像这样:
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)
};
这是一个非常棒的jumpstart,但我认为你错过了@ 3nigma答案中的某些功能。也就是说,我不确定在没有返回服务器响应的情况下做出某些请求(全部获得并发布一些帖子)是多少意义。我在send方法的末尾添加了另一行 - 'return x.responseText;' - 然后返回每个'ajax.send'调用。 – Sam 2014-08-13 10:37:38
@Sam [通常]不能返回其异步请求。您应该在回调中处理回复。 – Petah 2014-08-13 11:18:16
@Sam里面有一个例子:'ajax.get('/ test.php',{foo:'bar'},function(responseText){alert(responseText);});' – Petah 2014-08-13 21:22:10
你可以使用以下功能:
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();
}
您可以在这些链接在线尝试类似的解决方案:
也可以为请求添加一些输入变量(将用于xmlhttp.send(request);) – 2016-10-18 10:43:09
@PavelPerna,因为这里的示例是一个'GET',因此您可以将它们添加到请求中,但是更一般的是,我和你在一起,我真的想过更新答案,接受请求参数作为函数的参数,还要传递方法('GET'或'POST'),但是阻止了我我希望这里的答案尽可能简单,让人们尽可能快地尝试。其实,我讨厌太长时间太长的一些其他答案,因为他们正试图做到完美:) – AbdelHady 2016-10-19 14:11:21
您可以根据浏览器得到正确的对象
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();
}
和后到:
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);
}
这可能会帮助:
function doAjax(url, callback) {
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
从几下面的例子小组合创建了这个简单的作品:
function ajax(url, method, data, async)
{
method = typeof method !== 'undefined' ? method : 'GET';
async = typeof async !== 'undefined' ? async : false;
if (window.XMLHttpRequest)
{
var xhReq = new XMLHttpRequest();
}
else
{
var xhReq = new ActiveXObject("Microsoft.XMLHTTP");
}
if (method == 'POST')
{
xhReq.open(method, url, async);
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhReq.send(data);
}
else
{
if(typeof data !== 'undefined' && data !== null)
{
url = url+'?'+data;
}
xhReq.open(method, url, async);
xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhReq.send(null);
}
//var serverResponse = xhReq.responseText;
//alert(serverResponse);
}
// Example usage below (using a string query):
ajax('http://www.google.com');
ajax('http://www.google.com', 'POST', 'q=test');
或者如果你的参数是对象(S) - 未成年人额外的代码调整:
var parameters = {
q: 'test'
}
var query = [];
for (var key in parameters)
{
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]));
}
ajax('http://www.google.com', 'POST', query.join('&'));
双方应充分浏览器+版本兼容。
这里值得在for循环中使用hasOwnProperty吗? – kibibu 2015-02-13 00:05:53
我正在寻找包括承诺与Ajax和排除jQuery。有关于HTML5 Rocks的文章介绍了ES6承诺(可以用Q之类的承诺库进行填充),然后使用我从文章中复制的代码片段。
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();
});
}
注:我也写了an article about this。
这是真正有用的,因为我正在做一个递归的长轮询机制! – super 2015-12-21 09:52:39
如果你不想包含JQuery,我会尝试一些轻量级的AJAX库。
我的最爱是reqwest。这只是3.4kb和很好的建立了:https://github.com/ded/Reqwest
下面是与reqwest样本GET请求:
reqwest({
url: url,
method: 'GET',
type: 'json',
success: onSuccess
});
现在,如果你想要的东西更轻巧,我想尝试microAjax在仅仅0.4kb: https://code.google.com/p/microajax/
这是对这里的所有代码:
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)}};
下面是一个示例调用:
microAjax(url, onSuccess);
我认为microAjax存在一个问题,当你调用它两次(因为众多的“this”,我认为必须有碰撞)。 我不知道如果调用两个“新的microAjax”是一个很好的解决方法,是吗? – 2015-05-24 13:47:28
:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if(xhr.status == 200){
console.log(xhr.responseText);
} else if(xhr.status == 400) {
console.log('There was an error 400');
} else {
console.log('something else other than 200 was returned');
}
}
}
xhr.open("GET", "mock_data.json", true);
xhr.send();
或者,如果你想使用Browserify捆绑你的模块使用起来node.js中您可以使用superagent:
var request = require('superagent');
var url = '/mock_data.json';
request
.get(url)
.end(function(err, res){
if (res.ok) {
console.log('yay got ' + JSON.stringify(res.body));
} else {
console.log('Oh no! error ' + res.text);
}
});
这里有一个JSFiffle不JQuery的
http://jsfiddle.net/rimian/jurwre07/
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
var url = 'http://echo.jsontest.com/key/value/one/two';
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
} else if (xmlhttp.status == 400) {
console.log('There was an error 400');
} else {
console.log('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
};
loadXMLDoc();
那么它只是一个4步轻松proceess,
我希望它帮助
Step 1.
商店参考XMLHttpRequest对象
var xmlHttp = createXmlHttpRequestObject();
Step 2.
检索XMLHttpRequest对象
function createXmlHttpRequestObject() {
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
Step 3.
使用XMLHttpRequest对象
function process() {
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
// retrieve the name typed by the user on the form
item = encodeURIComponent(document.getElementById("input_item").value);
// execute the your_file.php page from the server
xmlHttp.open("GET", "your_file.php?item=" + item, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
}
Step 4.
执行的请奥波异步HTTP请求atically当从服务器
function handleServerResponse() {
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4) {
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200) {
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseText;
document.getElementById("put_response").innerHTML = xmlResponse;
// restart sequence
}
// a HTTP status different than 200 signals an error
else {
alert("There was a problem accessing the server: " + xmlHttp.statusText);
}
}
}
收到消息,我知道这是一个相当古老的问题,但现在有在本地提供newer browsers一个更好的API。fetch()
方法允许您发出Web请求。 例如,为了从/get-data
要求的一些JSON:
var opts = {
method: 'GET',
body: 'json',
headers: {}
};
fetch('/get-data', opts).then(function (response) {
return response.json();
})
.then(function (body) {
//doSomething with body;
});
详情请参阅here。
老,但我会尝试,也许有人会觉得这个信息有用。
这是您需要执行GET
请求和获取某些JSON
格式化数据所需的最少量代码。这仅适用于现代的浏览器,如最新版本的Chrome ,FF,Safari浏览器,歌剧院和微软边缘。
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data.json'); // by default async
xhr.responseType = 'json'; // in which format you expect the response to be
xhr.onload = function() {
if(this.status == 200) {// onload called even on 404 etc so check the status
console.log(this.response); // No need for JSON.parse()
}
};
xhr.onerror = function() {
// error
};
xhr.send();
还检查了新Fetch API这是一个基于承诺,替代XMLHttpRequest API。
使用@Petah答案作为一个巨大的帮助资源。我已经编写了我自己的AJAX模块,简称AJ:https://github.com/NightfallAlicorn/AJ并非所有的东西都经过了测试,但它适用于JSON的获取和发布。您可以随意复制和使用源代码。我还没有看到明显的接受答案,所以我认为这是可以发布。
这个版本在普通的情况下如何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();
});
}
该函数返回promise。下面是关于如何使用功能和处理承诺它返回一个例子:
get('foo.txt')
.then((data) => {
// Do stuff with data, if foo.txt was successfully loaded.
})
.catch((err) => {
// Do stuff on error...
});
如果需要加载,您可以使用JSON.parse()
装入的数据转换成JS对象一个JSON文件。
您也可以将req.responseType='json'
整合到函数中,但不幸的是有no IE support for it,所以我会坚持JSON.parse()
。
使用'XMLHttpRequest'您可以异步尝试加载文件。这意味着您的代码将继续执行,而您的文件将在后台加载。为了在脚本中使用文件的内容,您需要一种机制,在文件完成加载或加载失败时告诉您的脚本。这就是*承诺*派上用场的地方。还有其他方法可以解决这个问题,但是我认为* promises *是最方便的。 – Rotareti 2016-08-29 11:08:52
@Rotareti移动浏览器是否支持这种方法? – bodruk 2017-01-24 16:19:17
只有更新的浏览器版本支持它。通常的做法是在最新的ES6/7/..中编写代码,并使用Babel或类似方法将其转换回ES5以获得更好的浏览器支持。 – Rotareti 2017-01-24 17:34:56
var load_process = false;
function ajaxCall(param, response) {
if (load_process == true) {
return;
}
else
{
if (param.async == undefined) {
param.async = true;
}
if (param.async == false) {
load_process = true;
}
var xhr;
xhr = new XMLHttpRequest();
if (param.type != "GET") {
xhr.open(param.type, param.url, true);
if (param.processData != undefined && param.processData == false && param.contentType != undefined && param.contentType == false) {
}
else if (param.contentType != undefined || param.contentType == true) {
xhr.setRequestHeader('Content-Type', param.contentType);
}
else {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
}
else {
xhr.open(param.type, param.url + "?" + obj_param(param.data));
}
xhr.onprogress = function (loadTime) {
if (param.progress != undefined) {
param.progress({ loaded: loadTime.loaded }, "success");
}
}
xhr.ontimeout = function() {
this.abort();
param.success("timeout", "timeout");
load_process = false;
};
xhr.onerror = function() {
param.error(xhr.responseText, "error");
load_process = false;
};
xhr.onload = function() {
if (xhr.status === 200) {
if (param.dataType != undefined && param.dataType == "json") {
param.success(JSON.parse(xhr.responseText), "success");
}
else {
param.success(JSON.stringify(xhr.responseText), "success");
}
}
else if (xhr.status !== 200) {
param.error(xhr.responseText, "error");
}
load_process = false;
};
if (param.data != null || param.data != undefined) {
if (param.processData != undefined && param.processData == false && param.contentType != undefined && param.contentType == false) {
xhr.send(param.data);
}
else {
xhr.send(obj_param(param.data));
}
}
else {
xhr.send();
}
if (param.timeout != undefined) {
xhr.timeout = param.timeout;
}
else
{
xhr.timeout = 20000;
}
this.abort = function (response) {
if (XMLHttpRequest != null) {
xhr.abort();
load_process = false;
if (response != undefined) {
response({ status: "success" });
}
}
}
}
}
function obj_param(obj) {
var parts = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return parts.join('&');
}
我Ajax调用
var my_ajax_call=ajaxCall({
url: url,
type: method,
data: {data:value},
dataType: 'json',
async:false,//synchronous request. Default value is true
timeout:10000,//default timeout 20000
progress:function(loadTime,status)
{
console.log(loadTime);
},
success: function (result, status) {
console.log(result);
},
error :function(result,status)
{
console.log(result);
}
});
用于中止先前的请求
my_ajax_call.abort(function(result){
console.log(result);
});
从youMightNotNeedJquery.com + JSON.stringify
var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(JSON.stringify(data));
简单的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')
我们可以指定该请求应该是异步的(真),默认情况下,或同步(假)与可选的第三个参数。
// 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.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.');
}
}
}
之前请注意,虽然有很多的答案这里建议监听_readystatechange_,现在的浏览器现在支持_XMLHttpRequest_的_load_,_abort_,_progress_和_error_事件虽然只关心_load_虽然)。 – 2015-03-31 16:27:18
@ImadoddinIbnAlauddin例如当它的主要功能(DOM遍历)不需要时。 – SET 2015-07-10 22:05:35
@Imad是因为JQuery是一个Javascript库,当人们决定使用完全非强制性的语言,而且实际上并没有为该语言添加任何新东西时,这真是令人讨厌。 – DaemonOfTheWest 2015-12-27 21:51:42