【问题标题】:Ajax POST in javascript without jquery没有jquery的javascript中的Ajax POST
【发布时间】:2014-03-27 16:00:17
【问题描述】:

我需要从我必须使用 ajax POST 在客户端(Javascript)中创建的 URL 中使用来自服务器端的 JSON 对象。

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

我应该在function(e) 中使用什么?

我不应该在这里使用 Jquery。

【问题讨论】:

标签: javascript ajax json post


【解决方案1】:

你需要send()你的请求。

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();

【讨论】:

  • 我想在 url 中发帖。
  • 如果你想发帖,请将你想发帖的内容放在.send。这是正确的回答。
【解决方案2】:

这是我编写的一个函数,它总是用于 ajax 请求、帖子...随便

 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)
 }

我认为只有 chrome 支持 responseType='json'; 通过删除responseType='json';,您可以使用

JSON.parse()

所以:

JSON.parse(oReq.response)

要从这个 ajax 调用中获得响应,您可以选择 3 种方式

1.在我/或你的情况下

c.response
//your
oReq.response

2.使用这个

this.response // i always use this.

3.e.target

e.target.response

ajax函数说明:

这个ajax函数有6个可用参数

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

只需要 2 个 urlcallback(简单获取请求)

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)

在你的情况下,你使用 post

所以你需要 4 个参数

urlcallbacktype(post in your case)formdata

所以:

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

fd 有两种构建方式

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

或者你也可以发布整个表格

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

您也可以添加进度事件功能

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

上传进度相同

回调函数就是这样的

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))
}

如果您有任何问题,请尽管提出。

【讨论】:

    猜你喜欢
    • 2016-05-26
    • 2017-08-27
    • 2021-01-19
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多