Reputation: 13558
I have a ruby hash where the keys are urls and the values are integers. I convert the hash to JSON and I'm wondering if I'll be able to send the JSON inside a url via an AJAX request and then pull that JSON from a params hash.
Also, I am going to be sending a JSONifyed ruby hash back to the client. If I have a success callback in my AJAX function where I receive the data in a data
variable, how do I parse that JSON with JQuery?
Please let me know if I need to be more specific.
Upvotes: 6
Views: 20155
Reputation: 18354
Yes, you can with no problem. No manual encoding/decoding needed!
Your code would be like this:
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);
}
});
As you can see, no manual encoding/decoding was needed. Jquery handles it all!
Hope this helps. Cheers
PS: If, for some reason, you need to encode/decode your json manually for url use javascript's encodeURIComponent(string)
and $.parseJSON(jsonString)
methods.
Upvotes: 11
Reputation: 69915
Yes you can pass the json object as a get or post parameter.
In order to parse json string using Jquery you can use $.parseJSON.
Upvotes: 1