How to use JSON.stringify safely

I get a JSON object, which then build to insert var. The .log console looks like this:

console.log(send_me_along)

{"provider_url":"https://www.site.com/","description":"Stuff, you’ll need to blah blah","title":"Person detail view & engagement","url":"https://www.site.com/","version":"1.0","provider_name":"site","type":"link"}

Then in ajax beforeSend I try to pass this:

settings.data += '&embed_data=' + send_me_along;

Here it breaks. I do not know why. You? Something send_me_along breaks, and the JSON object never makes it rails.

Started POST "/st" for 127.0.0.1 at 2012-01-12 17:20:25 -0800
Parameters: {"utf8"=>"✓", "authenticity_token"=>"MzDImoksi56IZ1Fa4ldM8jaFyBy61xaWt4bf3z0/3UQ=", "comment"=>{"content"=>"https://www.site.com", "mentions"=>"https://www.site.com"}, "commit"=>"", "embed_data"=>"{\"provider_url\":\"https://www.site.com/\",\"description\":\"Stuff, you’ll need to blah blah.\",\"title\":\"Person detail view ", "engagement\",\"url\":\"https://www.site.com/\",\"version\":\"1.0\",\"provider_name\":\"site\",\"type\":\"link\"}"=>nil, "id"=>"ae86c5b7a6"}

It seems that the message also interfered with the header. is there something w jQuery needs to do when using settings.data so as not to allow strict data to break everything?

thank

+5
source share
3 answers

If you are trying to pass a JSON string as a url parameter, you need to encode it so that special characters that have a value in the URL (for example, ampersands) do not break. So something like:

settings.data += '&embed_data=' + encodeURIComponent(send_me_along)

encodeURIComponent() MDN.

+5

encodeURIComponent .

settings.data += '&embed_data=' + encodeURIComponent( send_me_along );
+1

ajax?

$.ajax(
  //...
  data: {
     stuff: "something"...
  }
);

Let jquery handle ampersands.

0
source

All Articles