如何在此Jsfiddle中使用JQuery访问JSON对象的属性? [英] How can I access the properties of my JSON object using JQuery in this Jsfiddle?

查看:92
本文介绍了如何在此Jsfiddle中使用JQuery访问JSON对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我一直在隐约尝试使用这个问题示例,以使用jsfiddle进行测试.我正在寻找一个JQuery可排序的小部件,但是首先我需要弄清楚如何访问正在创建的对象中的属性-在经过很多混乱之后,现在要画一些空白!

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?**/);
    };   

编辑1

抱歉,没有完整的Jsfiddle链接,已保存并对其进行了编辑.

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

编辑2

使用JsonLint创建有效的Json.现在我可以执行警报了,但是我不确定如何访问其中的属性!

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

编辑3

已将Jsfiddle链接更新为最新版本.

Updated Jsfiddle link to latest version.

推荐答案

您需要将JSON字符串解析为一个对象:

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);
    };

您的小提琴有语法错误.由于jQuery中没有toJSON方法,因此未创建JSON.为了使用每个迭代器读取类别,它们必须是类似以下的数组:

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: ...]

这篇关于如何在此Jsfiddle中使用JQuery访问JSON对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆