jquery ajax编码数据
我有这段代码(如下)..
$.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"
});
我使用它来将数据传递到 Web 服务,但问题是其中是否有任何像这样的字符 (, / ? : @ & = + $ #)。我已经放入了一个可以正常工作的encodeURIComponent,然后在Web 服务中我再次将它们放回去。
我想问的是是否有更好的方法来实现这一点?每次在传递字符串之前我都必须对字符串进行编码,这似乎有点疯狂。
谢谢
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.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将数据作为对象而不是字符串传递:
pass data thru as an object instead of a string:
该网络服务是属于您的还是您使用别人的网络服务? Web 服务不接受 (, / ? : @ & = + $ #) 的原因是什么?
jQuery $.ajax 默认 contentType 是 application/x-www-form-urlencoded 这意味着 jQuery 将对内容进行编码。但是,由于您指定了不同的 contentType,因此数据不会被编码,因此您必须进行自己的编码。
或者,您可以尝试删除 contentType 选项并正常传入您的内容(不使用 encodeURICompnent)。
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 (, / ? : @ & = + $ #)?
jQuery $.ajax default contentType is application/x-www-form-urlencoded which 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.
Alternatively, you could try to remove the contentType option and pass in your content normally (without encodeURICompnent).