简体   繁体   中英

How can I access the properties of my JSON object using JQuery in this Jsfiddle?

Yeah I've been vaguely trying to use this questions example to test something out with jsfiddle. I'm looking to build a JQuery sortable widget, but first I need to find out how I can access properties in the object I'm creating - drawing up a bit of a blank at the moment after a lot of messing about with it!

Live Fiddle!

$('#ParentCategoryId').change(function() {
    var data =
{
"categories": {
    "category1": {
        "Name": "Maps",
        "Id": 3,
        "orderInList": 1
    },
    "category2": {
        "Name": "Books",
        "Id": 2,
        "orderInList": 2
    }
}
};

$.ajax({
    url: 'http://jsfiddle.net/echo/jsonp/',
    dataType: 'jsonp',
    data: data,
    success: function(data) {
        show_response(data);
    },
    type: 'GET'
});
});            

function show_response(data) {
    $.each(data, function()
    {        
        alert(/**How could I access say, category1's Name property in here?**/);
    };   

Edit 1

Didn't get the full Jsfiddle link sorry, saved and edited it in.

Edit 2

Used JsonLint to create valid Json. Now I can get the alert to execute, but I'm unsure how to access the properties within!

Edit 3

Updated Jsfiddle link to latest version.

You need to parse the JSON string into an object:

function show_response(data) {
    data = $.parseJSON(data);
    $.each(data, function(position, value)
    {        
       alert(value.name);
    };

EDIT: Your fiddle has syntax errors. The JSON is not created as there is no toJSON method in jQuery. In order to read your categories using an each iterator, they need to be an array like:

categories = [name: "Book", value: ...], [name: "Movie", value: ...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM