English 中文(简体)
建造支松树结构
原标题:Building a json tree structure

我将透过一个json 字符串通过一个 ajax 请求,

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

为了建立这支Json弦, 我有一位听众, 当发射后,

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

这是构建 jSon 字符串 的正确方式吗? 我是否应该使用 jQuery 方法创建json 对象( 如果存在的话), 并添加元素, 然后将json 对象转换为字符串, 而不是自己创建json 字符串?

最佳回答

我建议做的是建立一个 object ,然后当您准备好发送到服务器时,通过 Json.stringize 将对象序列化。

例如,您可能会有一个名为 data 的物体 :

var data = {};

...其中您可以定期添加属性 :

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

data 是一个阵列:

var data = [];

...你加了东西:

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

然后,当你准备发送的时候,

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

由于您正在将对象传送到 ajax , 您不必担心 JSON 字符串的 URL 编码; jQuery 将为您这样做 。

JSON.stringify 的定义是ECMAScript5的一部分,由许多浏览器自行提供,但当然,我们许多人必须支持过时的浏览器版本。在这些情况下,你可以用“JSONshim”来添加JSON.stringify 到一个没有它的环境,其中之一是JSON的创始人Douglas Crockford在https://github.com/douglascrockford/JSON-js/"rel="nofollow"他的gitub页面

问题回答

如果使用 jQuery, 您可以使用 < a href=> "http://code.google.com/ p/jquery- json/" rel="nofollow">jquery- json , 一个用 JavaScript 和 jQuery 处理 JSON 的非常方便的插件 。

用法 :

var jsonString = $.toJSON(myObject);




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签