简体   繁体   English

在传递给jQuery ajax数据参数之前清洗字符串

[英]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. 在ASP.Net上使用jQuery ajax时,我们需要在所需参数上通过字符串json传递数据。 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 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. 如果我理解正确,.NET页需要在POST参数内以JSON编码的字符串提交数据。 You can use jquery-json to accomplish this: 您可以使用jquery-json完成此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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