Recently, I encountered a problem in the process of small program development. That is, the array object passed by me when I adjusted the back-end interface could not be parsed normally, and would become such a string as [Object Object]. Naturally, the back end cannot use such data either. As shown in figure:
Here’s my data:
And then, here’s my request data
My mater_arr data prints out as a normal array, but it does pass as an object object string. After a long search, I came up with a solution that uses JSON serialization, i.e. Json.stringify to parse objects into strings.
This, I think is also a better solution, but the need for back-end cooperation, and then the object string parsing out; However, my back – end comrade refused to help, so I went back to research.
After looking for a long time, I finally found a solution, but quite troublesome, is to use the following data structure to upload:
const data = {
id: 1.title: 'test'
}
// The data that we want to upload normally
/ / such as mater_arr is a [{id: 1, the title: 'stone'}, {id: 2, the title: 'diamond'}] such data
this.mater_arr.forEach((item, idx) = > {
for (const key in item) {
const _data = mater_arr[idx][key] = item[key]
data.push(_data)
}
})
Copy the code
In this way, the data structure passed over is actually:
{
id: 1, title: 'test ', mater_arr[0][id]:1, mater_arr[0][title]: Stones,... }Copy the code
I think it has something to do with the way the backend receives the mater_arr array object. In fact, WHEN I do this, I want to use the FormData object to try to see if I can pass, but it turns out that the small program does not have this object, speechless…
In conclusion, this should be a protocol problem in the transmission process, right? Because our backend required that the content-type of the process we uploaded must be X-www-form-urlencoded, it seemed that this Type of data could not be nested with objects, so the object object display problem was caused. Here are some common format differences:
Role format | | | | — – | — – | — – | | application/x – WWW – form – urlencoded | default transmission format, Through the key, the value, & the way patchwork | | multipart/form – data | can upload key-value pairs, can also transfer files | | application/json | represents the data of the json string, need the back-end processing |
I certainly think json.stringify is a good solution, and now the backend framework seems to handle these requests quite simply and automatically.
Another solution is to pass in the same parameters as I did above, which I’ve only used in my case, and it’s possible, perhaps, to do with the back-end values. $_POST[‘xx’] = $_POST[‘xx’]
In a word, in a word. In the past, I didn’t pay much attention to the format difference of these requests. I started to use the default format of the tool. I don’t know what happened when ENCOUNTERING problems.