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);
}
}
}
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.');
}
}
}
34
在浏览器中的纯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();
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);
33
A verry good solution with pure javascript is here
/*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
<?php
//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();
4
A small combination from a couple of the examples below and created this simple piece:
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');
OR if your parameters are object(s) - minor additional code adjustment:
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('&'));
两者都应该完全兼容浏览器版本 .
12
旧但我会尝试,也许有人会发现这个信息有用 .
这是执行 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();
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();
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();
});
}
22 回答
我希望它有所帮助
Step 1.
存储对XMLHttpRequest对象的引用Step 2.
检索XMLHttpRequest对象Step 3.
使用XMLHttpRequest对象发出异步HTTP请求Step 4.
从服务器收到消息时自动执行使用上面的@Petah作为一个巨大的帮助资源 . 我在这里编写了我自己的AJAX模块,简称为:https://github.com/NightfallAlicorn/AJ并非所有内容都经过测试,但它适用于JSON的get和post . 你还没有看到明确接受的答案,所以我认为这可以发布 .
使用XMLHttpRequest .
简单的GET请求
简单的POST请求
我们可以指定请求应该是异步(true),默认或同步(false)以及可选的第三个参数 .
我们可以在调用
httpRequest.send()
之前设置 Headers我们可以通过在调用
httpRequest.send()
之前将httpRequest.onreadystatechange
设置为函数来处理响应在浏览器中的纯JavaScript中:
或者,如果您想使用Browserify使用node.js捆绑您的模块 . 你可以使用superagent:
这可能有所帮助:
使用以下代码段,您可以非常轻松地执行类似的操作,如下所示:
这是片段:
我的ajax电话
用于中止先前的请求
使用“vanilla”JavaScript:
使用jQuery:
您可以根据浏览器获取正确的对象
使用正确的对象,可以将GET抽象为:
和POST:
http://ajaxpatterns.org/XMLHttpRequest_Call
如果你不想包含JQuery,我会尝试一些轻量级的AJAX库 .
我最喜欢的是reqwest . 它只有3.4kb并且内置得很好:https://github.com/ded/Reqwest
以下是reqwest的示例GET请求:
现在,如果你想要更轻量级的东西,我会以0.4kb的价格尝试microAjax:https://code.google.com/p/microajax/
这是所有代码:
这是一个示例电话:
A verry good solution with pure javascript is here
A small combination from a couple of the examples below and created this simple piece:
OR if your parameters are object(s) - minor additional code adjustment:
两者都应该完全兼容浏览器版本 .
旧但我会尝试,也许有人会发现这个信息有用 .
这是执行
GET
请求并获取某些JSON
格式化数据所需的最少量代码 . 这仅适用于现代浏览器,如 Chrome , FF , Safari , Opera 和 Microsoft Edge 的最新版本 .另请查看新的Fetch API,它是XMLHttpRequest API的基于承诺的替代品 .
HTML:
PHP:
我知道这是一个相当古老的问题,但现在newer browsers中有一个更好的API本机可用 .
fetch()
方法允许您发出Web请求 . 例如,要从/get-data
请求一些json:有关详细信息,请参阅here .
这是一个没有JQuery的JSFiffle
http://jsfiddle.net/rimian/jurwre07/
普通 ES6/ES2015 这个版本怎么样?
该函数返回promise . 这是一个关于如何使用该函数并处理它返回的promise的示例:
如果需要加载json文件,可以使用JSON.parse()将加载的数据转换为JS对象 .
你也可以将req.responseType='json'集成到函数中,但不幸的是有no IE support for it,所以我会坚持使用
JSON.parse()
.我正在寻找包含承诺与ajax和排除jQuery . 在HTML5 Rocks上有一篇关于ES6承诺的文章(可以使用像Q这样的承诺库进行填充)然后使用我从文章中复制的代码片段 .
注意:我也写了an article about this .
来自youMightNotNeedJquery.com
JSON.stringify
您可以使用以下功能:
您可以在以下链接上在线尝试类似解决方案:
https://www.w3schools.com/xml/tryit.asp?filename=tryajax_first
https://www.w3schools.com/xml/tryit.asp?filename=tryajax_callback