Fetch 和 jQuery Ajax 帖子有什么不同? [英] What is different between Fetch and jQuery Ajax post?

查看:19
本文介绍了Fetch 和 jQuery Ajax 帖子有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将其作为 jquery ajax 进行发布以使其正常工作.

I tried it as jquery ajax for post it work correctly.

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

data will be hardcoded, but the code is one dynamic value.

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

我使用 web fetch api 来发布,它失败了.

I use web fetch api to post, it failed.

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

工作,如果我使用 $.ajax

Worked if i use $.ajax

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

推荐答案

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

Both methods work, as you can see below. You forgot to add the .then(r=>r.json()) decoding bit after the fetch request:

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>

但是,重要的是,您的后端要实现这些步骤才能使 fetch POST 工作:

It is important, however, that your backend implements these steps in order to make the fetch POST work:

  • $json=file_get_contents(php://input); 接收php中的数据
  • 使用$data=json_decode($json);
  • 解码
  • $json=file_get_contents(php://input); to receive the data in php
  • decode it using $data=json_decode($json);

这篇关于Fetch 和 jQuery Ajax 帖子有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆