如何在JQuery中使用JSFiddle echo功能?

时间:2011-08-25 17:09:05

标签: jquery json jsfiddle

我已经阅读了jsFiddle用户指南,了解他们的JSON echo feature,但是没有运气生成一个有效的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的简单转换就足够了。

3 个答案:

答案 0 :(得分: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);
    }
});

Live Demo

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

Demo with FireBug Console on View(无需启动开发者控制台查看返回)

答案 1 :(得分:12)

您也可以使用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);
  }
});

答案 2 :(得分:5)

这样的事情:

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

JS Fiddle example

基本上,将url函数的$.ajax部分指向/echo/jsonp/,您应该设置好。 JSFiddle的文档说/echo/json/也有效,但看起来特定的网址目前正在下降;但是,使用JSONP服务而不指定回调工作正常。

相关问题