jQuery:带有 html 实体的 ajax POST
我一直在使用 jQuery ajax & 发送表单。 $(this).serialize 到 php &数据库并且它运行得很好。现在我遇到的情况是,我无法使用序列化形式,而是从不同的输入字段生成字符串,问题是它似乎在该过程中丢失了一些 URL 实体。
例如,“&phone=+358123456789”结果“&phone= 358123456789”丢失了加号字符,最终在数据库中出现空格。 “&phone=%2B358123456789”工作正常。
因为除了“+”之外可能还有很多其他字符可能会丢失,所以我问是否有一个类似于 php 的 htmlentities 的函数可以转换字符串?我尝试过 javascript 的 escape() & unescape() 没有成功,并且干扰了 jquery 的 .text() & .html() 但结局也很糟糕。
I've been sending forms with jQuery ajax & $(this).serialize to php & database and it has worked perfectly. Now I have situation where I can't use serialized form but generate a string from different input fields instead and the problem is that it appears to lose some URL entities in the process.
for example "&phone=+358123456789" turns out "&phone= 358123456789" losing the plus character and ends up with whitespace to the database. "&phone=%2B358123456789" works fine though.
as there might be lots of other chars than "+" that could be lost, so I'm asking if there's a function similar to php's htmlentities that would convert a string? I've tried javascript's escape() & unescape() without success and meddled with jquery's .text() & .html() but that ended poorly aswell.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在数据字符串中使用 encodeURIComponent 。
use encodeURIComponent in your data string.
您仍然可以将数据作为对象传递到
$.ajax()
,例如:(或 AJAX 速记)方法 只需传递
{ param: value, param2: value }
对象,您将在其中放置.serialize()
之前。 此方法将调用encodeURIComponent()
内部,因为这就是$.param()
它使用的是:)You can still pass the data as an object to your
$.ajax()
(or AJAX shorthand) methods, for example:You just pass the
{ param: value, param2: value }
object where you would have put.serialize()
before. This method will callencodeURIComponent()
internally since that's what$.param()
that it uses does :)