你能通过网址发送JSON吗?

Jus*_*zer 6 ruby ajax jquery json ruby-on-rails

我有一个ruby哈希,其中键是url,值是整数.我将哈希转换为JSON,我想知道我是否能够通过AJAX请求在URL中发送JSON,然后从params哈希中提取该JSON.

另外,我将把JSONifyed ruby​​哈希发送回客户端.如果我在AJAX函数中成功回调,我在data变量中接收数据,如何用JQuery解析JSON?

如果我需要更具体,请告诉我.

Edg*_*ado 11

是的,你可以毫无问题.无需手动编码/解码!

你的代码是这样的:

var jsonParam = '{"name":"Edgar"}'; //Sample json param
$.ajax({
  ...  
  type: "get", //This sends in url
  data: {jsonParam: jsonParam}, //This will encode your json for url automatically
  dataType: "json", //With this the response will be automatically json-decoded!
  success: function(response){ //Assuming your server output was '{"lastName":"Villegas"}' as string
     alert(response.lastName);
  }
});
Run Code Online (Sandbox Code Playgroud)

如您所见,不需要手动编码/解码.Jquery处理这一切!

希望这可以帮助.干杯

PS:如果出于某种原因,你需要手动编码/解码你的json以便使用javascript encodeURIComponent(string)$.parseJSON(jsonString)方法.