Jquery ajax 编码数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5263708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery ajax encoding data
提问by tmutton
I have this code (below)..
我有这个代码(如下)。
$.ajax
({
type: "POST",
url: "../WebServices/Feedback.svc/sendfeedback",
dataType: 'json',
async: false,
data: '{"stars": "' + stars + '", "rating" : "' + rating + '", "note" : "' + encodeURIComponent(note) + '", "code" : "' + code + '", "permission" : "' + permission + '"}',
contentType: "application/json; charset=utf-8"
});
I am using this to pass in data to a web service but the problem is if there are any characters in there like this (, / ? : @ & = + $ #). I have put in an encodeURIComponent which works fine and then in the web service I put them back again.
我正在使用它来将数据传递给 Web 服务,但问题是那里是否有这样的字符 (, / ? : @ & = + $ #)。我已经放入了一个可以正常工作的 encodeURIComponent,然后在 Web 服务中我又把它们放回去了。
What i'm asking is if there is a better way of accomplishing this? It seems a bit crazy that I have to encode the string each time before passing it through..
我要问的是是否有更好的方法来实现这一点?每次传递之前我都必须对字符串进行编码,这似乎有点疯狂。
Thanks
谢谢
采纳答案by Quad Coders
Is the web service belong to you or do you use someone else's web service? What was the reason the web service is not accepting (, / ? : @ & = + $ #)?
Web 服务是属于您的还是您使用其他人的 Web 服务?Web 服务不接受 (, / ? : @ & = + $ #) 的原因是什么?
jQuery $.ajaxdefault contentType is application/x-www-form-urlencodedwhich mean jQuery will encode the content. However, since you have specify different contentType, the data is not encoded thus you have to do your own encoding.
jQuery $.ajax默认 contentType 是application/x-www-form-urlencoded这意味着 jQuery 将对内容进行编码。但是,由于您指定了不同的 contentType,数据未编码,因此您必须进行自己的编码。
Alternatively, you could try to remove the contentTypeoption and pass in your content normally (without encodeURICompnent).
或者,您可以尝试删除contentType选项并正常传递您的内容(没有encodeURICompnent)。
$.ajax
({
type: "POST",
url: "../WebServices/Feedback.svc/sendfeedback",
dataType: 'json',
async: false,
data: '{"stars": "' + stars + '", "rating" : "' + rating + '", "note" : "' + note + '", "code" : "' + code + '", "permission" : "' + permission + '"}',
});
回答by James
pass data thru as an object instead of a string:
将数据作为对象而不是字符串传递:
$.ajax
({
...
data: {stars: stars, rating: rating...(etc)}
});