如何使用 $.ajax(jQuery 或 Zepto)发布对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11109795/
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 10:12:02  来源:igfitidea点击:

How do I POST an array of objects with $.ajax (jQuery or Zepto)

jqueryajaxrestzepto

提问by SimplGy

I'd like to POST an array of objects with $.ajax in Zepto or Jquery. Both exhibit the same odd error, but I can't find what I'm doing wrong.

我想在 Zepto 或 Jquery 中使用 $.ajax 发布一组对象。两者都表现出相同的奇怪错误,但我找不到我做错了什么。

The data saves to the server when sent using a test client like 'RestEasy', and I can see the request getting mangled in the browser's net panel, so I believe JS is the culprit.

使用“RestEasy”等测试客户端发送数据时,数据会保存到服务器,我可以看到请求在浏览器的网络面板中被破坏,所以我相信 JS 是罪魁祸首。

If I send an array of objects as the data property of a POST, they are not properly sent.

如果我发送一个对象数组作为 POST 的数据属性,它们将无法正确发送。

Data object:

数据对象:

var postData = [
    { "id":"1", "name":"bob"}
  , { "id":"2", "name":"jonas"}
  ]

Request:

要求:

$.ajax({
  url: _saveDeviceUrl
, type: 'POST'
, contentType: 'application/json'
, dataType: 'json'
, data: postData
, success: _madeSave.bind(this)
//, processData: false //Doesn't help
});

Request body as seen in the browser:

在浏览器中看到的请求正文:

"bob=undefined&jonas=undefined"

This can be seen more directly by using the $.param method that both jQuery and Zepto use to prepare POST data.

通过使用 jQuery 和 Zepto 用于准备 POST 数据的 $.param 方法,可以更直接地看到这一点。

$.param(
  [
    { "id":"1", "name":"bob"}
  , { "id":"2", "name":"jonas"}
  ]
)
// Output: "bob=undefined&jonas=undefined"

So it seems like the preparation that these libraries do for complex post data is different than I expect.

因此,这些库为复杂的后期数据所做的准备似乎与我预期的不同。

I see this answer, but I don't want to send the data as a query param as I'm POSTing lots of content. How do I send an array in an .ajax post using jQuery?

我看到了这个答案,但我不想将数据作为查询参数发送,因为我正在发布大量内容。 如何使用 jQuery 在 .ajax 帖子中发送数组?

What is the correct way to send multiple objects over POST using jQuery/Zepto?

使用 jQuery/Zepto 通过 POST 发送多个对象的正确方法是什么?

Using $.ajax({... data: JSON.stringify(postData) ...}) sends non-mangled content, but the server doesn't like the format.

使用 $.ajax({... data: JSON.stringify(postData) ...}) 发送未损坏的内容,但服务器不喜欢这种格式。

Update:Seems like JSON.stringify sends correctly formatted content. The issue is that the server side is very, very specific about the structure of the object that it wants. If I add or remove any properties from the object, it will fail the whole process rather than using the properties that do match. This is inconvenient because it's nice to use server-sent content as a view model, but view models get changed. ...Still working on the best solution.

更新:似乎 JSON.stringify 发送格式正确的内容。问题是服务器端对它想要的对象的结构非常非常具体。如果我从对象中添加或删除任何属性,它将使整个过程失败,而不是使用匹配的属性。这很不方便,因为使用服务器发送的内容作为视图模型很好,但是视图模型会发生变化。...仍在研究最佳解决方案。

回答by SimplGy

Be sure to stringifybefore sending. I leaned on the libraries too much and thought they would encode properly based on the contentType I was posting, but they do not seem to.

请务必stringify在发送之前。我过于依赖库,认为它们会根据我发布的 contentType 正确编码,但它们似乎没有。

Works:

作品:

$.ajax({
    url: _saveAllDevicesUrl
,   type: 'POST'
,   contentType: 'application/json'
,   data: JSON.stringify(postData) //stringify is important
,   success: _madeSave.bind(this)
});

I prefer this method to using a plugin like $.toJSON, although that does accomplish the same thing.

与使用 $.toJSON 之类的插件相比,我更喜欢这种方法,尽管它确实可以完成相同的事情。

回答by Ricardo Alvaro Lohmann

Try the following:

请尝试以下操作:

$.ajax({
  url: _saveDeviceUrl
, type: 'POST'
, contentType: 'application/json'
, dataType: 'json'
, data: {'myArray': postData}
, success: _madeSave.bind(this)
//, processData: false //Doesn't help
});

回答by Simon

edit:I guess it's now starting to be safe to use the native JSON.stringify()method, supported by most browsers(yes, even IE8+ if you're wondering).

编辑:我想现在使用大多数浏览器都支持的原生JSON.stringify()方法开始变得安全了(是的,如果您想知道,甚至是 IE8+)。

As simple as:

就这么简单:

JSON.stringify(yourData)


You should encode you data in JSON before sending it, you can't just send an object like this as POST data.

您应该在发送数据之前用 JSON 对数据进行编码,您不能将这样的对象作为 POST 数据发送。

I recommand using the jQuery json pluginto do so. You can then use something like this in jQuery:

我建议使用jQuery json 插件来执行此操作。然后你可以在 jQuery 中使用这样的东西:

$.post(_saveDeviceUrl, {
    data : $.toJSON(postData)
}, function(response){
    //Process your response here
}
);

回答by Nuno Dias

Check this example of post the array of different types

检查这个发布不同类型数组的例子

function PostArray() {
    var myObj = [
        { 'fstName': 'name 1', 'lastName': 'last name 1', 'age': 32 }
      , { 'fstName': 'name 2', 'lastName': 'last name 1', 'age': 33 }
    ];

    var postData = JSON.stringify({ lst: myObj });
    console.log(postData);

    $.ajax({
        type: "POST",
        url: urlWebMethods + "/getNames",
        data: postData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            alert(response.d);
        },
        failure: function (msg) {
            alert(msg.d);
        }
    });
}

If using a WebMethod in C# you can retrieve the data like this

如果在 C# 中使用 WebMethod,您可以像这样检索数据

[WebMethod]
    public static string getNames(IEnumerable<object> lst)
    {
        string names = "";
        try
        {
            foreach (object item in lst)
            {
                Type myType = item.GetType();
                IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

                foreach (PropertyInfo prop in props)
                {
                    if(prop.Name == "Values")
                    {
                        Dictionary<string, object> dic = item as Dictionary<string, object>;
                        names += dic["fstName"];
                    }
                }
            }
        }
        catch (Exception ex)
        {
             names = "-1";
        }
        return names;
    }

Example in POST an array of objects with $.ajax to C# WebMethod

将带有 $.ajax 的对象数组 POST 到 C# WebMethod 中的示例