Dojo拖放问题:将目标容器中的数据转换为JSON

时间:2012-05-01 14:20:32

标签: javascript json dojo drag-and-drop

我有两个DND conatainers,SourceContainer和TargetContainer SourceContainer有一些json数据,例如:

Apple 
Orange 
Banana

使用以下Json:

var json = {"fruits": [
           {"fruitId": 1, "fruitName": "Apple", "fruitDesc": "This is an Apple"},
           {"fruitId": 2, "fruitName": "Orange", "fruitDesc": "This is an Orange"},
           {"fruitId": 3, "fruitName": "Banana", "fruitDesc": "This is a Banana"}
        ]
    };

var results="";
   for(var i=0;i<json.fruits.length;i++){
     results += '<div class="dojoDndItem ">' + '<span style="visibility: hidden">' + json.fruits[i].fruitId + '</span>' + json.fruits[i].fruitName  + '</div>';
   }

我的SourceContainer

<div><label>Fruits</label></div> 
<div dojoType="dojo.dnd.Source" id="source1" copyonly="false" delay="8" class="container dojoDndSource dojoDndTarget dojoDndContainer">
<div dojoType="dojo.dnd.Source" ></div> results </div>

我的TargetContainer

<div><label>Basket</label></div>
<div dojoType="dojo.dnd.Source"  id="source2" copyonly="false" descending="true" delay="8" class="container dojoDndSource dojoDndTarget dojoDndContainer">
<div dojoType="dojo.dnd.Source" ></div>
</div>

<button id="toJsonBtn" data-dojo-type="dijit.form.Button" type="button">ToJson</button>

现在,当我将“Apple”和Banana拖到TargetContainer并单击按钮时,我希望TargetContainer中的数据在Json中转换。

这样做的任何想法。感谢任何帮助。谢谢

注意:强制不使用JQuery :(

1 个答案:

答案 0 :(得分:0)

我想出了如何解决它。如果有人感兴趣,下面是解决方案;

我们的Json

var json = {"fruits": [
               {"fruitId": 1, "fruitName": "Apple", "fruitDesc": "This is an Apple"},
               {"fruitId": 2, "fruitName": "Orange", "fruitDesc": "This is an Orange"},
               {"fruitId": 3, "fruitName": "Banana", "fruitDesc": "This is a Banana"}
            ]
        };

目标容器中的项目

Apple 
Orange 
Banana

创建目标容器

var fruitListContainer = new dojo.dnd.Source("fruitNode");

dojo.connect(dojo.byId('toJsonBtn'), 'onclick', function() {
  var target_container = fruitListContainer.getAllNodes();
  var fruit_arr = [];
  for(var i=0;i<target_container.length;i++){
      var fruit_results = target_container[i].childNodes[0].nodeValue;
      roles_arr.push(fruit_results);
  }
var result={};
result["fruits"]=fruit_arr;
alert(JSON.stringify(result));

警报输出将是(这是必需的):

{"fruits":["Apple","Orange","Banana"]}

注意: 如果需要任何解释,我很乐意提供帮助。