jQuery:在JSON中混合字符串和Javascript对象列表

jQuery: Mixing Strings and List of Javascript Objects in JSON

本文关键字:Javascript 对象 列表 字符串 混合 JSON jQuery      更新时间:2023-09-26

我想做的可能很简单,但是我不太熟悉jQuery,我不知道如何做到这一点。

我想发送一些数据作为JSON到ASP。网络控制器。数据包含一些字符串和一个对象列表。

代码看起来像这样:

视图:

    $(document).ready(function () {
    var stuff = [
        { id: 1, option: 'someOption' },
        { id: 2, option: 'someOther' },
        { id: 3, option: 'anotherOne' }
    ];
    things = JSON.stringify({ 'things': things });
    var dataRow = {
        'String1': 'A String',
        'String2': 'AnotherOne'
    }
    dataRow = JSON.stringify(dataRow);
    var sendData = dataRow + things;
    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Backend/DoStuffWithStuff',
        data: sendData,
        success: function () {
            alert('Success!');
        },
        failure: function (response) {
            alert('Fail! :(');
        }
    });
});

控制器:

    public class Stuff
    {
        public int id { get; set; }
        public string option{ get; set; }
    }
    public void DoStuffWithStuff(string String1, String2, List<Thing> things)
    {
        //Do my Stuff
    }

任何想法都会很棒!:)

不需要对json数据进行字符串化。你只需要创建一个要发送的对象然后输入

var jsonObject = {
   'string' : 'string',
   'object' : {
       'stirng': 'string'
   }
};
$.ajax({type: "POST", url: DotNetScript, data: jsonObject})
.done(function(dataBack){
   //what to do with data back
});

目前看起来还不算太糟!只有几件事……

[HttpPost]
public void DoStuffWithStuff(string String1, String2, List<Stuff> things)
{
    //Do my Stuff
}

在这里,你并没有给string2一个类型。我假设这是一个打字错误,但这是次要的部分。

同样,在那个方法中,注意它在顶部有HttpPost。在你的javascript中:

$.ajax({
    ...
    type: 'POST',
    ...
});

你指定POST,所以你必须使方法支持POST(你也可以摆脱get在这种情况下通过改变类型为get,然后删除属性,但我不确定你的"东西"需要什么…)

var stuff = [
    { id: 1, option: 'someOption' },
    { id: 2, option: 'someOther' },
    { id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
    'String1': 'A String',
    'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;

你实际上并没有把东西传递到你的方法中,这可能会有帮助…

这是用正确的JSON传递重写的ajax方法(用于您在这里尝试做的事情)。

$(document).ready(function () {
    var stuff = [
        { id: 1, option: 'someOption' },
        { id: 2, option: 'someOther' },
        { id: 3, option: 'anotherOne' }
    ];
    var dataRow = {
        String1: 'A String',
        String2: 'AnotherOne'
        things: stuff
    }
    $.ajax({
        dataType: 'json',
        type: 'POST',
        url: '/Backend/DoStuffWithStuff',
        data: sendData,
        success: function () {
            alert('Success!');
        },
        failure: function (response) {
            alert('Fail! :(');
        }
    });
});