Better JSON data structure

后端 未结 2 634
逝去的感伤
逝去的感伤 2021-01-24 03:01

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 obje

相关标签:
2条回答
  • 2021-01-24 03:44

    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.

    0 讨论(0)
  • 2021-01-24 03:49

    Your commented code passes a different object to the non-commented code

    Commented data (non-working):

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

    Uncommented data (working):

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

    the original commented ajax request should be:

    $.getJSON(url, searchCriteria, function (data) {
        if (data.length) {
            alert('Success');
        }
    });
    
    0 讨论(0)
提交回复
热议问题