dov*_*mir 575
使用"vanilla"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>
Run Code Online (Sandbox Code Playgroud)
使用jQuery:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
Run Code Online (Sandbox Code Playgroud)
Pet*_*tah 216
使用以下代码段,您可以非常轻松地执行类似的操作,如下所示:
ajax.get('/test.php', {foo: 'bar'}, function() {});
Run Code Online (Sandbox Code Playgroud)
这是片段:
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)
};
Run Code Online (Sandbox Code Playgroud)
Wil*_*unn 116
我知道这是一个相当古老的问题,但现在有一个更好的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;
});
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参见此处
Abd*_*ady 103
您可以使用以下功能:
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();
}
Run Code Online (Sandbox Code Playgroud)
您可以在以下链接上在线尝试类似解决方案:
Rot*_*eti 40
在普通的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();
});
}
Run Code Online (Sandbox Code Playgroud)
该函数返回一个promise.下面是一个如何使用该函数并处理它返回的promise的示例:
get('foo.txt')
.then((data) => {
// Do stuff with data, if foo.txt was successfully loaded.
})
.catch((err) => {
// Do stuff on error...
});
Run Code Online (Sandbox Code Playgroud)
如果需要加载json文件,可以使用JSON.parse()
将加载的数据转换为JS对象.
你也可以集成req.responseType='json'
到这个功能,但不幸的是没有IE支持,所以我会坚持JSON.parse()
.
Raf*_*fay 37
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"
Run Code Online (Sandbox Code Playgroud)
http://ajaxpatterns.org/XMLHttpRequest_Call
Har*_*rel 33
简单的GET请求
httpRequest = new XMLHttpRequest()
httpRequest.open('GET', 'http://www.example.org/some.file')
httpRequest.send()
Run Code Online (Sandbox Code Playgroud)
简单的POST请求
httpRequest = new XMLHttpRequest()
httpRequest.open('POST', 'http://www.example.org/some/endpoint')
httpRequest.send('some data')
Run Code Online (Sandbox Code Playgroud)
我们可以指定请求应该是异步(true),默认或同步(false)以及可选的第三个参数.
// Make a synchronous GET request
httpRequest.open('GET', 'http://www.example.org/some.file', false)
Run Code Online (Sandbox Code Playgroud)
我们可以在调用之前设置标头 httpRequest.send()
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Run Code Online (Sandbox Code Playgroud)
我们可以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.');
}
}
}
Run Code Online (Sandbox Code Playgroud)
bru*_*ops 29
您可以根据浏览器获取正确的对象
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;
}
Run Code Online (Sandbox Code Playgroud)
使用正确的对象,可以将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();
}
Run Code Online (Sandbox Code Playgroud)
和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);
}
Run Code Online (Sandbox Code Playgroud)
Ali*_*ned 17
我正在寻找包括承诺与ajax和排除jQuery.有一篇关于HTML5 Rocks的文章讨论了ES6的承诺(可以使用像Q这样的promise库进行填充),然后使用我从文章中复制的代码片段.
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();
});
}
Run Code Online (Sandbox Code Playgroud)
注意:我还写了一篇关于此的文章.
tfo*_*ont 15
以下几个例子中的一个小组合创建了这个简单的部分:
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');
Run Code Online (Sandbox Code Playgroud)
或者,如果您的参数是对象 - 次要的附加代码调整:
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('&'));
Run Code Online (Sandbox Code Playgroud)
两者都应完全兼容浏览器+版本.
Rya*_*yan 15
如果你不想包含JQuery,我会尝试一些轻量级的AJAX库.
我最喜欢的是reqwest.它只有3.4kb并且内置得很好:https://github.com/ded/Reqwest
以下是reqwest的示例GET请求:
reqwest({
url: url,
method: 'GET',
type: 'json',
success: onSuccess
});
Run Code Online (Sandbox Code Playgroud)
现在,如果你想要更轻量级的东西,我只需0.4kb即可试用microAjax: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)}};
Run Code Online (Sandbox Code Playgroud)
这是一个示例电话:
microAjax(url, onSuccess);
Run Code Online (Sandbox Code Playgroud)
Bla*_*res 13
旧但我会尝试,也许有人会发现这个信息有用.
这是执行GET
请求和获取某些JSON
格式化数据所需的最少量代码.这仅适用于现代浏览器,如最新版本的Chrome,FF,Safari,Opera和Microsoft Edge.
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();
Run Code Online (Sandbox Code Playgroud)
另请查看新的Fetch API,它是XMLHttpRequest API的基于承诺的替代品.
尝试使用 Fetch Api ( Fetch API )
fetch('http://example.com/movies.json').then(response => response.json()).then(data => console.log(data));
Run Code Online (Sandbox Code Playgroud)
它真的很清楚,而且是 100% 的香草。
来自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));
Run Code Online (Sandbox Code Playgroud)
您可以使用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);
Run Code Online (Sandbox Code Playgroud)
您还可以使用该fetch()
方法来获取,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);
});
}
});
Run Code Online (Sandbox Code Playgroud)
另一方面,如果您只是尝试进行POST
数据传输并且不需要服务器响应,则最短的解决方案是使用navigator.sendBeacon()
:
const data = JSON.stringify({
example_1: 123,
example_2: 'Hello, world!',
});
navigator.sendBeacon('example.php', data);
Run Code Online (Sandbox Code Playgroud)
这可能有所帮助:
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();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
667160 次 |
最近记录: |