如何使用 JQuery 发布 JSON 数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6255344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:36:05  来源:igfitidea点击:

How can I use JQuery to post JSON data?

jqueryajaxjsonposthttp-post

提问by Jonas

I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:

我想将 Json 发布到同一服务器上的 Web 服务。但我不知道如何使用 JQuery 发布 Json。我试过这个代码:

$.ajax({
    type: 'POST',
    url: '/form/',
    data: {"name":"jonas"},
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"}but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.

但是使用此 JQuery 代码,数据不会作为 Json 在服务器上接收。这是服务器上的预期数据:{"name":"jonas"}但使用 JQuery 服务器接收name=jonas。或者换句话说,它是“urlencoded”数据而不是 Json。

Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?

有没有办法使用 JQuery 以 Json 格式而不是 urlencoded 数据发布数据?还是我必须使用手动 ajax 请求?

回答by lonesomeday

You're passing an object, nota JSON string. When you pass an object, jQuery uses $.paramto serialize the object into name-value pairs.

您正在传递一个对象,而不是一个 JSON 字符串。当您传递一个对象时,jQuery 使用$.param将对象序列化为名称-值对。

If you pass the data as a string, it won't be serialized:

如果您将数据作为字符串传递,它将不会被序列化:

$.ajax({
    type: 'POST',
    url: '/form/',
    data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

回答by Ninh Pham

Base on lonesomeday's answer, I create a jpostthat wraps certain parameters.

基于lonesomeday的答案,我创建了一个jpost包装某些参数的。

$.extend({
    jpost: function(url, body) {
        return $.ajax({
            type: 'POST',
            url: url,
            data: JSON.stringify(body),
            contentType: "application/json",
            dataType: 'json'
        });
    }
});

Usage:

用法:

$.jpost('/form/', { name: 'Jonh' }).then(res => {
    console.log(res);
});

回答by Lee Harding

I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data

我尝试了 Ninh Pham 的解决方案,但在我调整它之前它对我不起作用 - 见下文。删除 contentType 并且不编码您的 json 数据

$.fn.postJSON = function(url, data) {
    return $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: 'json'
        });

回答by David Arun

The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.

最佳答案工作正常,但我建议在发送长表单或处理大数据时,在发布之前将您的 JSON 数据保存到变量中,这样会更清晰一些。

var Data = {
"name":"jonsa",
"e-mail":"[email protected]",
"phone":1223456789
};


$.ajax({
    type: 'POST',
    url: '/form/',
    data: Data,
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

回答by loretoparisi

Using Promiseand checking if the bodyobject is a valid JSON. If not a Promise rejectwill be returned.

使用Promise并检查body对象是否是有效的 JSON。如果不是,reject将返回一个 Promise 。

var DoPost = function(url, body) {
    try {
        body = JSON.stringify(body);
    } catch (error) {
        return reject(error);
    }
    return new Promise((resolve, reject) => {
        $.ajax({
                type: 'POST',
                url: url,
                data: body,
                contentType: "application/json",
                dataType: 'json'
            })
            .done(function(data) {
                return resolve(data);
            })
            .fail(function(error) {
                console.error(error);
                return reject(error);
            })
            .always(function() {
                // called after done or fail
            });
    });
}