JSON 转义字符
我有一个字符串提前终止,因为“&q”(我猜测)在原始字符串中被转义。如果我想保留 PHP 中的原始字符串,应该如何处理?
的原始字符串结果
'http://answers.onstartups.com/search?tab=active&q=fbi'
var_dump
'["http://answers.onstartups.com/search?tab=active'
JS
var linksStr = $("#links").val();
var matches = JSON.stringify(linksStr.match(/\bhttps?:\/\/[^\s]+/gi));
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
data: 'matches=' + matches,
url: 'publishlinks/check_links',
success:
function(response) {
alert(response);
}
})
check_links
$urls = $this->input->get('matches');
var_dump($urls);
I have a string that terminates prematurely because of '&q' (I'm guessing) being escaped in the original string. How should I handle this if I want to retain the original string in PHP?
Original string
'http://answers.onstartups.com/search?tab=active&q=fbi'
Result of var_dump
'["http://answers.onstartups.com/search?tab=active'
JS
var linksStr = $("#links").val();
var matches = JSON.stringify(linksStr.match(/\bhttps?:\/\/[^\s]+/gi));
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
data: 'matches=' + matches,
url: 'publishlinks/check_links',
success:
function(response) {
alert(response);
}
})
check_links
$urls = $this->input->get('matches');
var_dump($urls);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以对 JSON 字符串进行编码:
您也可以这样写:
然后 jQuery 应该为您执行编码步骤。
You can encode the JSON string:
You could also write it like:
and then jQuery should do the encode step for you.
从 jQuery .val() 返回的网址是:
.match()
正则表达式将返回一个数组:JSON.stringify() 正确输出为:
但是,如果您将其附加为 raw 这里的 GET 参数:
那么 URL 中转义的
&
将终止 GET 值。使用encodeURIComponent
Your url as returned from jQuery .val() is:
The
.match()
regex will return an array:Which JSON.stringify() correctly outputs as:
However if you attach it as raw GET parameter here:
Then the enescaped
&
in the URL will terminate the GET value. UseencodeURIComponent
将
data: 'matches=' + matches,
更改为:
data: {"matches": matches},
。这样 jQuery 就会为你计算出编码。否则,您必须使用 encodeURIComponent() 对 uri 进行编码
Change
data: 'matches=' + matches,
To:
data: {"matches": matches},
.So that jQuery will figure out the encoding for you. Otherwise you'll have to encode the uri using encodeURIComponent()