views:

27

answers:

3

Hello,

On using jQuery ajax on ASP.Net, we are required to pass the DATA through a string-ed json on the parameters needed. My only concern with this is with strings that has single & double quotes. I tried doing a replace on these and insert escape characters but unfortunately it just doesn't work.

help!

UPDATE

 var relativeName = $('#<%= txtRelativeName.ClientID %>').val().replace("'", "\'");

 $.ajax({ data: "{ relativeName: '" + relativeName + "'" });
A: 

Well, it would help to see your JSON string.

Which encoder do you use? Most escaping should be done there. If there are really too much quotes within your JSON it might be necessary to create ugly constructs like

\\\\

or

\\\\"

I didn't really understand the word "cleaning" in your subject. Note that you always need doublequoted keys name to generate a valid JSON string.

update

Whatever relativeName stores here, you should use native JSON parsing.

$.ajax({ data: window.JSON.stringify(relativeName));

window.JSON is available quite a while in all major browsers. If you need to support "old" browsers as well, watchout to www.json.org. You'll find en/decode javascript librarys there.

jAndy
just updated my post. please see above
Martin Ongtangco
+2  A: 

Forget about manually encoding parameters. Try like this:

var relativeName = $('#<%= txtRelativeName.ClientID %>').val();
$.ajax({ 
    data: JSON.stringify({ relativeName: relativeName }),
    ...
});
Darin Dimitrov
is JSON.stringify part of the jQuery core or the main framework itself? thanks man
Martin Ongtangco
from my native tongue, "Magaling ka!". thanks!
Martin Ongtangco
A: 

If I understand correctly, the .NET page needs data submitted as a JSON-encoded string inside a POST parameter. You can use jquery-json to accomplish this:

var encoded = $.toJSON({ some: 'parameter' }); 
$.post(
 url: 'something.aspx',
 data: {
   jsonstr: encoded
 }
}
pygorex1