20

我已经阅读了 jsFiddle 用户指南以了解他们的 JSON回显功能,但没有运气生成一个工作 jsFiddle 来使用 JQuery 回显 JSON 消息。

如何创建一个 jsFiddle 以从他们的指南中回显 JSON:

data: {
    json: JSON.encode({
        text: 'some text',
        array: [1, 2, 'three'],
        object: {
            par1: 'another text',
            par2: [3, 2, 'one'],
            par3: {}
        }
    }),
    delay: 3
}

提供的一个示例是在我从未使用过的 Mootools 中。因此,从 mootools 示例到 JQuery 的简单翻译就足够了。

4

3 回答 3

24
var data = {
        json: $.toJSON({
            text: 'some text',
            array: [1, 2, 'three'],
            object: {
                par1: 'another text',
                par2: [3, 2, 'one'],
                par3: {}
            }
        }),
        delay: 3
}


$.ajax({
    url:"/echo/json/",
    data:data,
    type:"POST",
    success:function(response)
    {
       console.log(response);
    }
});

现场演示

注意我添加了一个额外的资源.. jquery-json

在 View 上使用 FireBug 控制台进行演示(无需打开开发者控制台即可查看返回)

于 2011-08-25T19:45:23.837 回答
13

您还可以使用 JSON.stringify

$.ajax({
  url:"/echo/json/",
  data:{
    json: JSON.stringify({
        text: 'some text',
        array: [1, 2, 'three'],
        object: {
            par1: 'another text',
            par2: [3, 2, 'one'],
            par3: {}
        }
      }),
    delay: 3
  },
  type:"POST",
  success:function(response) {
    console.log(response);
  }
});

​</p>

于 2012-08-28T10:05:10.327 回答
6

像这样的东西:

$.get('/echo/jsonp/', { foo : 'bar', biz : 'buzz' })
    .success(function(data){ console.log (data) })

JS 小提琴示例

基本上,将你的函数url部分指向你应该被设置。JSFiddle 的文档说这也有效,但目前该特定 URL 似乎已关闭;不过,在不指定回调的情况下使用 JSONP 服务就可以了。$.ajax/echo/jsonp//echo/json/

于 2011-08-25T18:28:32.330 回答