问题描述
我环顾四周,我试图找到一个优雅的解决这一点,我还没有找到一个。我有一个ASMX Web服务在.NET中我试图调用需要的参数。
I've looked around, and I'm trying to find an elegant solution to this, and I'm yet to find one. I have an ASMX web service in .NET that I'm trying to call that requires parameters.
我使用在客户端jQuery来调用服务和我jQuery的code看起来是这样的:
I'm using jQuery on the client side to call the service and my jQuery code looks something like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/Reviews/HotelReview.asmx/SubmitReview",
data: "{'name': '" + name + "', " +
"'info': '" info + "'}",
processData: true,
beforeSend: function() { startSubmit(); },
complete: function() { submitComplete(); },
error: function(xhr) { submitError(xhr); },
success: function(msg) { submitSuccess(msg.d); }
});
它工作得很好,除非要么名称或信息包含 字符,一个单引号。很简单,因为我的JSON定义字段的值的末尾,是一个单引号。当这两个域中包含一个单引号,我得到的是一个内部服务器错误,但进一步检查使用的给我的结果(我不会打扰到它们张贴)表示单引号的问题。
It works very well, except when either name or info contain the ' character, a single quote. Simple enough, because my JSON defines the end of the value of the field and is a single quote. When either of these fields contains a single quote, all I get is an "Internal Server Error", but further inspection using Fiddler showed me the results (I won't bother to post them) indicating the single quote issue.
我已经把东西到位暂时删除单引号的客户端,并把它们放回在服务器端,但是这是远远优雅。是否有一个更优雅的方式来逃避这些单引号,这样我的code能工作吗?
I've put something in place temporarily to remove the single quotes on the client side and put them back in on the server side, but this is far from elegant. Is there a more elegant way to escape these single quotes so that my code can work?
推荐答案
规格说JSON中只能使用左右键和值双引号,以便尝试用双引号。我是pretty的确保您的错误将得到解决。
The specifications say that in JSON you can only use double-quotes around keys and values so try it with double quotes. I am pretty sure your error will be solved.
您可能需要使用 json.js 为en code /逃脱实际值的特殊字符,这样你就不会遇到问题包含值来说,还是从的。
You may want to use json.js to encode / escape special characters in the actual values so you don't run into problems with values containing " for instance, or the stringify method from http://www.json.org/js.html.
这篇关于提交与使用jQuery,Ajax和JSON单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!