如何在本版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();
});
}
该函数返回a的承诺。这里是一个例子如何使用函数和它的承诺:返回的句柄
get('foo.txt')
.then((data) => {
// Do stuff with data, if foo.txt was successfully loaded.
})
.catch((err) => {
// Do stuff on error...
});
如果你需要,你可以使用负载的JSON文件的数据转换JSON.parse()JS对象加载到参与。
所以,你可以把req.responseType='json'整合功能,但不幸的,没有IE的支持它,这样我会有JSON.parse()棒。
使用XMLHttpRequest可以异步尝试加载文件。这意味着您的代码将继续执行,而您的文件将在后台加载。为了在脚本中使用文件的内容,需要一种机制来告诉脚本文件何时完成加载或加载失败。这就是承诺的用武之地。有其他方法可以解决这个问题,但我认为承诺是最方便的。
@Rotareti移动浏览器支持这种方法吗?
只有更新的浏览器版本支持它。通常的做法是用最新的ES6/7/编写代码。并使用babel或类似工具将其发回ES5以获得更好的浏览器支持。
@Rotareti你能解释一下为什么这比简单的回调更方便吗?为了旧的浏览器支持,这一便利值得付出额外的努力吗?
@Lennartkloppenburg我认为这个答案很好地解释了这一点:stackoverflow.com/a/14244950/1612318"为了旧的浏览器支持,这个便利值得付出额外的努力吗?"承诺只是ES6/7附带的众多功能之一。如果使用蒸腾器,则可以编写最新的JS。这是值得的!
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"
http:///_ ajaxpatterns.org XMLHttpRequest呼叫
这能跨浏览器工作吗?
不要进行同步调用。使用xhreq.onload并使用回调。
@你能举个例子说明你的意思吗?
@fellowtranger oreq.οnlοad=函数()/*this.responsetext*/
@Kenansulayman同步调用有什么问题?有时它最适合。
@安德烈:没什么,只要你意识到你正在停止执行所有的操作,直到服务器的响应返回。没有什么特别糟糕的,但可能不完全适合某些用途。
@3nigma不在IE 10上工作
使用XMLHttpRequest。
简单的GET请求
httpRequest = new XMLHttpRequest()
httpRequest.open('GET', 'http://www.example.org/some.file')
httpRequest.send()
简单的邮件请求
httpRequest = new XMLHttpRequest()
httpRequest.open('POST', 'http://www.example.org/some/endpoint')
httpRequest.send('some data')
我们可以指定请求应该是TRUE(默认),异步或同步(假),一个可选的第三参数。
// 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.onreadystatechangeto a
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;
}
一个正确的对象,可能abstracted 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 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循环中使用hasownpropy是否值得?
我找了一个包括提供Ajax和jQuery的模块。它在这条岩石es6谈论HTML5承诺(承诺是一个图书馆polyfill样q)然后使用下面的代码片断从我copied软腭。
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();
});
}
注:在我写了关于这个的文章。
如果你不想使用jQuery,我尝试了一些轻量级的Ajax库。
我最喜欢的是reqwest。它只3.4kb和很好的建出:http:////reqwest DED github.com
这是一个一个GET请求reqwest示例:
reqwest({
url: url,
method: 'GET',
type: 'json',
success: onSuccess
});
现在如果你想要的东西,甚至更多的是,我microajax at a try大0.4kb:http://///P microajax code.google.com
这是所有的代码在这里:
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有问题,当你两次调用它时(因为有许多"这个",我认为,一定有碰撞)。我不知道叫两个"新微JAX"是不是一个很好的解决方法,是吗?
但我老想尝试,也许有人会发现这个信息有用。
这是最小的代码量你需要做一些JSONfetch a GET请求和格式化数据。这是只适用的现代浏览器的最新版本的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的可替代。
从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));
这可能帮助:
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();
}
Well it is just a 4 step easy 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对象异步HTTP请求
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.自动执行从服务器收到的邮件
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);
}
}
}
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 = '' ;
}
Load
Clear
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);
});
HTML:
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();
}
Let AJAX change this text
Change Content
PHP的:
$id = $_GET[id];
print"$id";
?>
单行ifs不需要大括号,没有人使用ie6,这可能是复制粘贴的,使用onload而不是onreadystatechange,捕捉可能递归调用的错误,xmlhttp是一个糟糕的变量名,只需调用它x。
这是一个没有jsfiffle jQuery
jsfiddle.net http:/ / / / / 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();
XMLHttpRequest的()
你可以使用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()
所以,你可以使用一个Promisefetch()方法获得一个对象的一个resolves 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);
});
}
});
navigator.sendbeacon()
在其他的手,如果你是一个简单的POSTN的数据并不需要从A服务器响应,在最短的解决方案将使用navigator.sendBeacon():
const data = JSON.stringify({
example_1: 123,
example_2: 'Hello, world!',
});
navigator.sendBeacon('example.php', data);
使用上面的答案为A"佩巨大的帮助资源。我写我自己的Ajax模块,这里称为AJ的短:http:////nightfallalicorn github.com AJ和测试,而不需要一个和我得到它后为JSON。你可以随意复制和使用源代码为你的愿望。我没回答,是公认的A T的湖泊,这是好的,所以我presume张贴。
在普通的JavaScript在浏览器:
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启动使用。你可以使用超级特工:
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);
}
});
一个良好的解决方案verry纯JavaScript是这里
/*create an XMLHttpRequest object*/
let GethttpRequest=function(){
let httpRequest=false;
if(window.XMLHttpRequest){
httpRequest =new XMLHttpRequest();
if(httpRequest.overrideMimeType){
httpRequest.overrideMimeType('text/xml');
}
}else if(window.ActiveXObject){
try{httpRequest =new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
httpRequest =new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
if(!httpRequest){return 0;}
return httpRequest;
}
/*Defining a function to make the request every time when it is needed*/
function MakeRequest(){
let uriPost ="myURL";
let xhrPost =GethttpRequest();
let fdPost =new FormData();
let date =new Date();
/*data to be sent on server*/
let data = {
"name" :"name",
"lName" :"lName",
"phone" :"phone",
"key" :"key",
"password" :"date"
};
let JSONdata =JSON.stringify(data);
fdPost.append("data",JSONdata);
xhrPost.open("POST" ,uriPost, true);
xhrPost.timeout = 9000;/*the time you need to quit the request if it is not completed*/
xhrPost.onloadstart = function (){
/*do something*/
};
xhrPost.onload = function (){
/*do something*/
};
xhrPost.onloadend = function (){
/*do something*/
}
xhrPost.onprogress =function(){
/*do something*/
}
xhrPost.onreadystatechange =function(){
if(xhrPost.readyState < 4){
}else if(xhrPost.readyState === 4){
if(xhrPost.status === 200){
/*request succesfull*/
}else if(xhrPost.status !==200){
/*request failled*/
}
}
}
xhrPost.ontimeout = function (e){
/*you can stop the request*/
}
xhrPost.onerror = function (){
/*you can try again the request*/
};
xhrPost.onabort = function (){
/*you can try again the request*/
};
xhrPost.overrideMimeType("text/plain; charset=x-user-defined-binary");
xhrPost.setRequestHeader("Content-disposition","form-data");
xhrPost.setRequestHeader("X-Requested-With","xmlhttprequest");
xhrPost.send(fdPost);
}
/*PHP side
//check if the variable $_POST["data"] exists isset() && !empty()
$data =$_POST["data"];
$decodedData =json_decode($_POST["data"]);
//show a single item from the form
echo $decodedData->name;
?>
*/
/*Usage*/
MakeRequest();