简体   繁体   English

构建一个json树结构

[英]Building a json tree structure

I will be passing a json string to a servlet via an ajax request : 我将通过ajax请求将json字符串传递给servlet:

function add() {
    $.ajax({
    url: "pathToServlet" ,
    dataType: "text",
    data: ({
        name : 'myJsonString'
    }),
    success: function(data) {
            alert('returned!!');
    });
}

To build up this json string I have a listener which when fired appends a new piece of json to string : 为了构建这个json字符串,我有一个监听器,在触发时将一个新的json附加到字符串:

var json = "";
json += "{ new json ..... }"

Is this the correct way to build up the jSon String ? 这是构建jSon String的正确方法吗? Should I be using jQuery methods to create a json object(if they exist) and add elements to it and then convert the json object to a string instead of creating the json string myself ? 我应该使用jQuery方法创建一个json对象(如果它们存在)并向其添加元素然后将json对象转换为字符串而不是自己创建json字符串?

What I would recommend doing is building up an object , and then when you're ready to send it to the server, serialize the object via JSON.stringify . 我建议做的是构建一个对象 ,然后当你准备好将它发送到服务器时,通过JSON.stringify序列化对象。

So for instance, you might have an object called data : 例如,您可能有一个名为data的对象:

var data = {};

...to which you might periodically add properties: ...您可以定期添加属性:

data.foo = "bar";
data.stuff = {nifty: "stuff"};

Or perhaps data is an array: 或者data可能是一个数组:

var data = [];

...to which you add things: ...你添加的东西:

data.push({nifty: "stuff"});

Then, when you're ready to send it: 然后,当你准备发送它时:

function add() {
    $.ajax({
    url: "<%=savePortlet%>" ,
    dataType: "text",
    data: {
        name : JSON.stringify(data)
    },
    success: function(data) {
            alert('returned!!');
    });
}

Because you're passing an object into ajax , you don't have to worry about URL-encoding the JSON string; 因为您将对象传递给ajax ,所以您不必担心对JSON字符串进行URL编码; jQuery will do it for you. jQuery会为你做的。

JSON.stringify is defined as part of ECMAScript5 and suppoted natively by many browsers, but of course many of us have to support outdated versions of browsers. JSON.stringify被定义为ECMAScript5的一部分,并被许多浏览器本地支持,但当然我们许多人必须支持过时的浏览器版本。 In those cases, you can get a "JSON shim" to add JSON.stringify to an environment that doesn't have it. 在这些情况下,您可以获得“JSON shim”以将JSON.stringify添加到没有它的环境中。 One of those is available from the originator of JSON, Douglas Crockford, on his github page . 其中一个可以从JSON的创始人Douglas Crockford那里获得,在他的github页面上

If using jQuery you can use jquery-json , a really handy plugin to handle JSON with JavaScript and jQuery. 如果使用jQuery,你可以使用jquery-json ,一个非常方便的插件,用JavaScript和jQuery处理JSON。

Usage: 用法:

var jsonString = $.toJSON(myObject);

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

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