简体   繁体   中英

cleaning strings before passing to jQuery ajax data parameter

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 + "'" });

Forget about manually encoding parameters. Try like this:

var relativeName = $('#<%= txtRelativeName.ClientID %>').val();
$.ajax({ 
    data: JSON.stringify({ relativeName: relativeName }),
    ...
});

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
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM