JSON转义字符

时间:2011-08-12 19:34:44

标签: php javascript json special-characters

我有一个过早终止的字符串,因为'& 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);

3 个答案:

答案 0 :(得分:3)

您可以对JSON字符串进行编码:

    data: 'matches=' + encodeURIComponent(matches),

你也可以这样写:

    data: { matches: matches }

然后jQuery应该为你做编码步骤。

答案 1 :(得分:3)

从jQuery .val()返回的url是:

'http://answers.onstartups.com/search?tab=active&q=fbi'

.match()正则表达式将返回一个数组:

new Array("http://answers.onstartups.com/search?tab=active&q=fbi")

哪个JSON.stringify()正确输出为:

["http://answers.onstartups.com/search?tab=active&q=fbi"]

但是,如果您将其作为原始 GET参数添加到此处:

 data: 'matches=' + matches,

然后,URL中的enescaped &将终止GET值。使用encodeURIComponent

答案 2 :(得分:2)

更改data: 'matches=' + matches,

收件人:data: {"matches": matches},

这样jQuery就会为你找出编码。否则,您必须使用encodeURIComponent()

对uri进行编码
相关问题