简体   繁体   中英

Ajax POST in javascript without jquery

I need to consume a JSON object from the server side from an URL which I have to create in the client side(Javascript) using ajax POST.

var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.responseType = "json";
oReq.onload = function(e) {
    var jsonObj = oReq.response;
   /* ... */
}

What am I supposed to use inside the function(e) ?

I am not supposed to use Jquery here.

You need to send() your request.

See this (slightly adjusted) example:

var oReq = new XMLHttpRequest();

oReq.open("POST", url, true);
oReq.responseType = "json";
oReq.onload = function(e) {
  var jsonResponse = oReq.response; // not responseText
  /* ... */
}
oReq.send();

Here is a function i wrote & always use for ajax requests,posts... whatever

 function ajax(a,b,e,d,f,g,c){
  // url,callback,type(get),FormData(null),uploadProgress,progress 
  c=new XMLHttpRequest;
  !f||(c.upload.onprogress=f);
  !g||(c.onprogress=g);
  c.onload=b;
  c.open(e||'get',a);
  c.send(d||null)
 }

I think that only chrome supports the responseType='json'; by removeing responseType='json'; you can get the json response by using

JSON.parse()

so:

JSON.parse(oReq.response)

to get the response from this ajax call you can choose between 3 ways

1.In my case / or your

c.response
//your
oReq.response

2.Using this

this.response // i always use this.

3.e.target

e.target.response

ajax function description:

This ajax function has 6 usable parameters

url, callback, type(get or post),FormData(or null),uploadProgress,progress

only 2 are necessary url and callback (simple get request)

ajax('url',function(){console.log(this.response)})
// it's better to use a function reference to avoid memory leaks
// like
function cb(){console.log(this.response)};
ajax('url',cb)

in your case you use post

so you need 4 parameters

url , callback , type(post in your case) , and the formdata

so:

ajax('url',callbackFunction,'post',fd);

where fd is build in 2 ways

var fd=new FormData();
fd.append('key','value');
ajax('url',callbackFunction,'post',fd);

or you can also post the whole form

var fd=new FormData(document.getElementsByTagName('form')[0]);
ajax('url',callbackFunction,'post',fd);

alternatively you can also add a progress event function

function progress(e){
 console.log(e.loaded/e.total*100)
}

same for the upload progress

and the callback function is something like that

function callbackFunction(e){
console.log(e.target.response);
console.log(this.response);
console.log(c.response);

// without the reponsetype

console.log(JSON.parse(e.target.response));
console.log(JSON.parse(this.response));
console.log(JSON.parse(c.response))
}

if you have any questions just ask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM