且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更好的JSON数据结构

更新时间:2022-10-19 12:32:50

您的两个示例未将相同的data参数传递给$.getJSON().

工作示例传递了此对象:

{
    Accrual: "A",
    Brand: "B"
}

无法正常工作的示例传递了此对象:

{
    searchCriteria: {
        Accrual: "A",
        Brand: "B"
    }
}

看到区别了吗?

要解决无法正常工作的示例(将{ searchCriteria: searchCriteria }传递到$.getJSON()的情况),可以将其更改为searchCriteria,从而删除了多余的对象层.

还请注意,这些是您在此处使用的JavaScript对象,而不是JSON.例如,您不必引用JSON所要求的诸如"Accrual"之类的属性名称. (引用属性名并没有什么害处,只是在JavaScript对象中是没有必要的.)知道何时使用JSON以及何时使用普通JavaScript对象是非常有用的.不一样的东西.

I have following jQuery code and it works fine and I am able to deserialize it in the server properly.

But when I tried to create a variable and pass that as a JSON object, it didn’t work. (The commented code didn’t work. The values didn’t reach the server correctly).

Reference: http://www.json.org/js.html

How can we define the variable correctly for the JSON object?

$(".searchCostPages").click(function () {


        var url = '/SearchDisplay/' + 'TransferSearchCriteria';

        //var searchCriteria = {};
        //searchCriteria.Accrual = "A";
        //searchCriteria.Brand = "B";

    //$.getJSON(url, {searchCriteria: searchCriteria
        //}, function (data) {
        //    if (data.length) {
        //        alert('Success');
        //    }

        //});

        $.getJSON(url, {
            "Accrual": "A",
            "Brand": "B"
                    }, function (data)
                    {
                        if (data.length)
                        {
                            alert('Success');
                        }

                    });



    });

Working - Network Header:

Not Working - Network Header:

UPDATE

Following code worked here. Also refer jQuery Ajax parameters are not formatted properly

    var searchCriteria = {};
    searchCriteria.Accrual = "A";
    searchCriteria.Brand = "B";

    $.getJSON(url, searchCriteria
    , function (data) {
        if (data.length) {
            alert('Success');
        }

    });


Your two examples do not pass the same data argument to $.getJSON().

The working example passes this object:

{
    Accrual: "A",
    Brand: "B"
}

The non-working example passes this object:

{
    searchCriteria: {
        Accrual: "A",
        Brand: "B"
    }
}

See the difference?

To fix the non-working example, where you pass { searchCriteria: searchCriteria } into $.getJSON(), you can change it to searchCriteria, thus removing the extra level of object.

Also note that these are JavaScript objects you're working with here, not JSON. For example, you don't have to quote the property names like "Accrual" as required by JSON. (It doesn't hurt anything to quote the property names, it just isn't necessary in a JavaScript object.) It's useful to know when you are dealing specifically with JSON and when you are dealing with ordinary JavaScript objects, because they're not the same thing.