gpt4 book ai didi

javascript - Ajax 的数据和 fetch API 的主体有什么区别?

转载 作者:行者123 更新时间:2023-12-01 23:36:41 26 4
gpt4 key购买 nike

来自 jQuery 的 ajax 函数

$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
console.log( "Data Saved: " + msg );
});

这是一个使用 fetch API 的请求

const data = { name: "John", data: "Boston" };
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: data,
};

const response = await fetch('/api ',options);
const responseData = await response.json();
console.log(responseData);

此外,这个获取实现如何在我的节点终端中产生错误?
例如,如果我使用数字而不是“Boston”,则意外标记会更改为“<”。

SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)

这两者之间有什么我应该注意的吗?
ajax的数据和fetch的body?

(我没有同时使用它们)

最佳答案

来自 the documentation我们可以看到...

When data is an object, jQuery generates the data string from the object's key/value pairs unless the processData option is set to false. For example, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf". If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.

fetch 不会那样做。但另外,您说过您通过将 Content-Type: application/json 作为 header 来发送 JSON,但您没有这样做(并且您的 jQuery 代码也没有这样做,它发送 URI 编码的数据)。

你必须自己做。如果要发送 JSON,请使用 JSON.stringify:

const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
};

如果要发送 URI 编码的数据,请使用 URLSearchParams:

const data = new URLSearchParams([ // Note this is an array of
["name", "John"], // [name, value] arrays
["data", "Boston"],
]);
const options = {
method: 'POST',
body: data,
};

如果要发送标准格式编码,请使用 FormData(与上面完全相同,但使用 FormData 而不是 URLSearchParams

Also how come this fetch implementation is producing an error in my node terminal ?If I use a digit instead of 'Boston' for example the Unexpected token changes to '<' .

SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)

因为您的对象被强制转换为字符串,并且它被强制转换为 [object Object]",从 o 开始,它是无效的 JSON。


旁注:您的 fetch 代码正在成为 API 中脚枪的猎物:fetch 仅在 network 错误上拒绝其 promise ,而不是关于 HTTP 错误。您不能假设来自 fetch 的已履行 promise 意味着您的请求成功,您必须检查:

const response = await fetch('/api ',options);
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const responseData = await response.json();
console.log(responseData);

关于javascript - Ajax 的数据和 fetch API 的主体有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65493949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com