简体   繁体   English

如何在此Jsfiddle中使用JQuery访问JSON对象的属性?

[英]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. 是的,我一直在模糊地尝试使用此问题示例来使用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! 我正在寻找一个JQuery可排序的小部件,但首先我需要弄清楚如何访问正在创建的对象中的属性-在经过大量的混乱之后,现在画出一点空白!

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 编辑1

Didn't get the full Jsfiddle link sorry, saved and edited it in. 抱歉,没有完整的Jsfiddle链接,保存并对其进行了编辑。

Edit 2 编辑2

Used JsonLint to create valid Json. 使用JsonLint创建有效的Json。 Now I can get the alert to execute, but I'm unsure how to access the properties within! 现在我可以执行警报了,但是我不确定如何访问其中的属性!

Edit 3 编辑3

Updated Jsfiddle link to latest version. 将Jsfiddle链接更新到最新版本。

You need to parse the JSON string into an object: 您需要将JSON字符串解析为一个对象:

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. 由于jQuery中没有toJSON方法,因此未创建JSON。 In order to read your categories using an each iterator, they need to be an array like: 为了使用每个迭代器读取类别,它们必须是类似以下的数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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