javascript - Post submission object problem in ajax?
世界只因有你
世界只因有你 2017-05-19 10:31:36
0
5
624

The general rule is to submit this kind of {a:1,b:2}data. If I want to submit {a:1,b:2,c:{d:3, e:{f:5}}}How to do this kind of embedded object?

世界只因有你
世界只因有你

reply all(5)
我想大声告诉你

The default contentType of axios is application/json. It supports your format
If you change application/x-www-form-urlencoded, you need to JSONize the fields with embedded objects

伊谢尔伦

The first
http header is set to

Content-Type: application/json

This JSON data can be formatted as a JSON string for submission

The second
http header is set to

Content-Type: application/x-www-form-urlencoded

At this time, a key needs to be passed in, and the js object also needs to be formatted into a JSON string, which probably looks like this

data=JSON.stringify({a:1})
过去多啦不再A梦

There is no essential difference between embedded objects and ordinary objects. Ajax submitted data needs to be jsonized.
The following is the ajax method I encapsulated, please refer to the xhr.setRequestHeader("Content-type", "application/json");JSON.stringify(data) part

function ajax(url, method, data, callback){
    var xhr = new XMLHttpRequest();
    xhr.timeout = 3000;
    xhr.ontimeout = function(){
        console.log('网络超时, 请稍后重试!');
    };
    xhr.onload = function(){
        var s = xhr.status;
        if((s >= 200 && s < 300) || s == 304){
            var res = xhr.responseText;
            typeof callback == 'function' && callback(res);
        }
    };
    xhr.onerror = function(){
        console.log('网络问题, 请稍后重试!');
    };
    data = (method != 'GET' && typeof data=='object')?JSON.stringify(data):null;
    xhr.withCredentials = true;
    xhr.open(method, url, true);
    xhr.setRequestHeader("Content-type", "application/json");
    try{
        xhr.send(data);
    }catch(e){
        console.log('网络不佳, 请稍后重试!');
    }
}
ajax('你的链接','POST',你的数据,执行成功后的回调);
習慣沉默

It depends on what you use to submit. If you think jquery can do automatic stringification for you, you can just throw it in directly.

Just do a JSON.stringify operation, and the backend will convert it back by itself.

phpcn_u1582

There is no essential difference between the regular data and the data you want to submit

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template