2014-09-02 59 views
0

这可能听起来像一个业余问题,但我坚持这一点。我正在使用jstree,目前我正在将jstree的数据加载为JSON。我想将JSON转换为变量。我怎么做?如何使用变量在jstree中获取数据

这是我的代码:

var treedata = ['{ "id" : "ajson1", "parent" : "#", "text" : "Customer" }', 
    '{ "id" : "ajson2", "parent" : "ajson1", "text" : "Order number" }', 
    '{ "id" : "ajson3", "parent" : "ajson1", "text" : "Date" }',  
    '{ "id" : "ajson4", "parent" : "#", "text" : "Company Name" }', 
    '{ "id" : "ajson5", "parent" : "#", "text" : "Contact Name" }', 
    '{ "id" : "ajson6", "parent" : "#", "text" : "Name1" }', 
    '{ "id" : "ajson7", "parent" : "#", "text" : "Product number1" }']; 

    $(function() { 
    $('#jstree').jstree({ 
    "checkbox" : { 
     "keep_selected_style" : false 
    }, 
    "core" : { 
     // so that create works 
     //ACITREE 
     "check_callback" : true, 
     'data' : treedata 
    }, 

    "types" : { 
     "default" : { 
     "icon" : "none" 
     }}, 

    "plugins" : [ "checkbox","dnd","sort","types",,"crrm"] 

    }); 
    $('#jstree').on("changed.jstree", function (e, data) { 
     console.log(data.selected); 
     //document.getElementById("test").innerHTML+=data.selected.text; 
    }); 
    // 8 interact with the tree - either way is OK 
    $('button').on('click', function() { 
     $('#jstree').jstree(true).select_node('child_node_1'); 
     $('#jstree').jstree('select_node', 'child_node_1'); 
     $.jstree.reference('#jstree').select_node('child_node_1'); 
    }); 
    }); 

请帮助。提前致谢。

+0

你的意思是你想要用包含JSON数组的变量替换该JSON数组? – 2014-09-02 06:19:08

+0

是的!以便我可以动态更改JSON中的值。 – 2014-09-02 06:21:09

+1

好的,这太简单了,作为答案发布。剪掉你的JSON块,用“myvar”取代它,然后在你的JSTree块定义一个变量之前......'var myvar = [YOURJSONHERE];' – 2014-09-02 06:22:07

回答

1

我不知道你是指向什么,但我想你的问题JSON

这里有关JSON的一些技巧可以帮助你。

  • []平均JSON阵列
  • {}平均JSON对象

下面的代码是JSON数组,你可以从它的循环或调用的对象定义的关键

var treedata = [{ "id" : "ajson1", "parent" : "#", "text" : "Customer" }, 
       { "id" : "ajson2", "parent" : "ajson1", "text" : "Order number" }]; 

通过循环获得对象

for(i = 0; i < treedata.length; i += 1) { 

    var obj = treedata[i]; 

    alert(obj.id); 
} 

获取对象的定义密钥

alert(treedata[0].id); 

,如果你想JSON对象转换为字符串

var string = JSON.stringify(treedata); 

转换成JSON再次

var json = JSON.parse(string); 

希望这些信息有用

+0

不,它是一串字符串。你需要将字符串解析为JSON来使用它,就像在你的第一个例子中一样 – 2014-09-02 07:00:23

+0

你用''''围绕对象'''删除这个''',它将是有效的json数组和对象 – Jack 2014-09-02 07:01:58

相关问题