如何像jQuery一样获取fetch()来发布数据? [英] How do I get fetch() to POST data the same way as jQuery does?

查看:55
本文介绍了如何像jQuery一样获取fetch()来发布数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从某些代码中删除jQuery.我仅将其用于POST操作,因此我想将其删除并改用fetch().但是我无法让fetch()使用相同的数据来工作.php文件运行正常,只是没有收到数据

I'm trying to remove jQuery from some code. I only use it for POST operations so I want to drop it and use fetch() instead. But I can't get fetch() to work using the same data. The php file is working OK, it is just not receiving the data

这将为以下两个测试案例设置测试数据:

This sets up the test data for both test cases below:

var toPostObj = new(Object);
toPostObj.action = "update+file";
toPostObj.arrays = [["2020-12-28", "23:20:56", "Trying from ztest", "9.jpg"]];

这适用于jQuery:

This works using jQuery:

$.post('toMariaDB.php', {  // url
    data: toPostObj 
}, function(data2, status, jqXHR) {
    console.log ("data2",data2);
});

这不适用于fetch():

This does not work using fetch():

fetch("toMariaDB.php", { 
    method: "POST", 
    body: toPostObj,   // using JSON.stringify(toPostObj) also doesn't work 
    headers: { "Content-type": "application/text; charset=UTF-8" } 
}) 
.then(response => response.text()) 
.then(text => console.log(text))//; 
.catch(error => {
    console.error(error)
})

出于调试目的,toMariaDB.php将从接收到的数据以及来自toMariaDB的任何其他消息中写入日志文件.
运行jQuery代码会将其写入日志文件:

For debugging purposes, toMariaDB.php writes out a log file of the data it receives and any other messages from toMariaDB.
Running the jQuery code writes this to the log file:

toMariaDB: I've ARRIVED
in toMariaDB 1=>Array
(
    [action] => update+file
    [arrays] => Array
        (
            [0] => Array
                (
                    [0] => 2020-12-28
                    [1] => 23:20:56
                    [2] => Trying from ztest
                    [3] => 9.jpg
                )

        )
)

这是toMariaDB.php期望的.
但是fetch()版本写道:

which is what toMariaDB.php expects.
But the fetch() version writes this:

toMariaDB: I've ARRIVED
in toMariaDB 1=>

无论我是否使用,fetch()的结果都是相同的

The result for fetch() is the same whether I use

body: toPostObj,   

body: JSON.stringify(toPostObj),

我用过

headers: { "Content-type": "application/text; charset=UTF-8" } 

因为toMariaDB.php返回文本,并且据我所知,标头描述了返回的内容
但以防万一我误解了,我尝试了

since toMariaDB.php returns text and, as I understand it, headers describes what is returned
but just in case I had misunderstood, I tried

headers: { "Content-type": "application/json; charset=UTF-8" } 

也是如此,但这也不起作用.

as well, but that didn't work either.

如何格式化主体,使其以与jQuery相同的形式到达toMariaDB.php?即

How can I format the body so that it arrives at toMariaDB.php in the same form as with jQuery? I.e.

toPostObj.action = "update+file";
toPostObj.arrays = [["2020-12-28", "23:20:56", "Trying from ztest", "9.jpg"]];

感谢您的帮助.

编辑

正如@ T.J.Crowder所建议的那样(感谢指向我),这是使用jQuery运行时网络"标签显示为请求有效载荷"的内容:

As suggested by @T.J.Crowder, (thanks for pointing me at that) here's what the Network tab shows as the Request Payload when running with jQuery:

data[action]: update+file
data[arrays][0][]: 2020-12-28
data[arrays][0][]: 23:20:56
data[arrays][0][]: Trying from ztest
data[arrays][0][]: 9.jpg

我不明白为什么它们不显示为data [arrays [[]] [0] [0]等,但是可以用.
(这是一个2D数组,因为toMariaDB.php必须能够处理多个数组.)

I don't understand why these don't show as data[arrays][0][0], etc., but it works.
(It's a 2D array because toMariaDB.php has to be able to process multiple arrays.)

使用fetch(),网络"标签的请求有效载荷"显示:

With fetch(), the Network tab Request Payload shows:

[object Object]

推荐答案

来自文档我们可以看到...

From the documentation we can see that...

当数据是对象时,除非 processData 选项设置为false,否则jQuery会根据对象的键/值对生成数据字符串.例如, {a:"bc",d:"e,f".} 转换为字符串"a = bc& d = e%2Cf" .如果该值是一个数组,则jQuery将根据传统设置(如下所述)的值,使用相同的键序列化多个值.例如,默认情况下, {a:[1,2]} 变为字符串"a%5B%5D = 1& a%5B%5D = 2" 传统:false 设置.

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.

(它没有这么说,但是它是递归的.)

(It doesn't say so, but it does it recursively.)

您的代码正在发送一个对象,该对象具有一个称为 data 的顶级属性,该属性的值就是您的 toPostObj ,而后者又具有包含字符串和数组值的属性.最终发送一个如下所示的POST正文:

Your code is sending an object with a single top-level property called data whose value is your toPostObj, which in turn has properties with string and array values. It ends up sending a POST body that looks like this:

data%5Baction%5D=update%2Bfile&data%5Barrays%5D%5B0%5D%5B%5D=2020-12-28&data%5Barrays%5D%5B0%5D%5B%5D=23%3A20%3A56&data%5Barrays%5D%5B0%5D%5B%5D=Trying+from+ztest&data%5Barrays%5D%5B0%5D%5B%5D=9.jpg

...这是这些参数:

...which is these parameters:

data[action]: update+file
data[arrays][0][]: 2020-12-28
data[arrays][0][]: 23:20:56
data[arrays][0][]: Trying from ztest
data[arrays][0][]: 9.jpg

您可以使用 URLSearchParams 对象:

You can replicate that with a URLSearchParams object like this:

var toPostObj = new URLSearchParams();
toPostObj.append("data[action]", "update+file");
toPostObj.append("data[arrays][0][]", "2020-12-28");
toPostObj.append("data[arrays][0][]", "23:20:56");
toPostObj.append("data[arrays][0][]", "Trying from ztest");
toPostObj.append("data[arrays][0][]", "9.jpg");
fetch("foo", {
    method: "POST",
    body: toPostObj
})
// ...

URLSearchParams 将为您处理URI转义等.

URLSearchParams will handle the URI-escaping etc. for you.

这篇关于如何像jQuery一样获取fetch()来发布数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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