【问题标题】:What is different between Fetch and jQuery Ajax post?Fetch 和 jQuery Ajax post 有什么不同?
【发布时间】:2021-08-24 04:47:22
【问题描述】:

我尝试将它作为 jquery ajax 发布它可以正常工作。

数据将被硬编码,但代码是一个动态值。

const data = {
  "retrieve": {
   "header": {
    "userID": 'xxx',
   },
   "body": {
     "code": code,
     "channel" : []  
   }
  }
}

我用web fetch api发帖,失败了。

const response = await fetch('https://api', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
const result = await response.json();

工作如果我使用 $.ajax

const response = await $.ajax({
  method: 'POST',
  url: 'https://api',
  data: JSON.stringify(data),
  contentType: 'application/json'
})

【问题讨论】:

标签: jquery api fetch


【解决方案1】:

这两种方法都有效,如下所示。您忘记在获取请求后添加.then(r=>r.json()) 解码位:

const api="https://jsonplaceholder.typicode.com/users";
const data = {
  "retrieve": {
   "header": {
"userID": 'xxx',
   },
   "body": {
 "code": 4711,
 "channel" : [7,2,8,3]  
   }
  }
};

(async function(){
const res1 = await fetch(api, {
  method: 'POST',
  headers: {
'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
}).then(r=>r.json());
console.log("fetch:",res1);

const res2 = await $.ajax({
  method: 'POST',
  url: api,
  data: JSON.stringify(data),
  contentType: 'application/json'
});
console.log("jQuery Post:",res2);
})()
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

然而,重要的是,您的后端实现这些步骤以使获取 POST 工作:

  • $json=file_get_contents(php://input);接收php中的数据
  • 使用$data=json_decode($json);对其进行解码

【讨论】:

  • 对不起,我没有完全描述,我确实在等待 res.json。我更新了最新的帖子。
猜你喜欢
  • 2017-08-18
  • 2021-10-27
  • 2016-01-21
  • 2017-11-09
  • 2013-10-06
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多