Jquery $ .get在hashtag之后剪切url

时间:2014-09-26 14:02:29

标签: javascript jquery ajax

我正在尝试将带有主题标签的网址发送到服务器,例如

  

/example.php?var1=tes#t&var2=value2

如果我在beforeSend函数中跟踪url,我看到该url只是

  

/example.php?var1=tes

删除了标签和包含主题标签之后的所有内容。如果我在使用$ .get()函数之前将hashtag编码为%23,那么一切都很完美。

这是一个示例代码。

    $.ajaxSetup(
    { 
        scriptCharset: "iso-8859-1",
        contentType: 'Content-type: text/plain; charset=iso-8859-1',
        cache: true,

        //zuerst alles encodieren, damit server keine fehler bekommt
        beforeSend: function(xhr, data) 
        {
            //wrong url
            console.log(data.url);
        }
    });

    //right url
    var link = "/example.php?var1=tes#t&var2=value2";
    $.get(link).done(function()
    {
        console.log("done");
    })

修改

服务器用iso-8859-1解码url,所以我需要将数据编码为iso。我在beforeSend函数中编写了一个脚本,它自动将url转换为iso,但它无法转换hashtag,因为data.url变量不包含hashtag。所以我需要在$ .ajaxSetup函数中访问完整的url(包括hashtag)。

4 个答案:

答案 0 :(得分:2)

encodeURIComponent()应用于您的网址字符串

答案 1 :(得分:1)

网址无效/格式错误。

主题标签必须是网址的最后一部分。

主题标签不是HTTP请求的部分,因此必须不在其中。

您不能将主题标签放在网址的中间,只有一种模式:

prot://domain/resource?parameter1=value1&parameter2=value2#fragment_identifier

如果以下情况不起作用,则根本不起作用:

/example.php?var1=test&var2=value2#hashval
  

使用URI引用对其执行检索操作时   标识资源,可选的片段标识符,分隔   由交叉阴影线(“#”)字符组成的URI由附加组成   用户代理在之后解释的参考信息   检索行动已成功完成。因此,事实并非如此   URI的一部分,但通常与URI结合使用。

http://www.w3.org/blog/2011/05/hash-uris/

证明:请求网址 - http://flowl.info/test#test

HTTP请求期间未使用片段标识符(#):

  

[26 / Sep / 2014:14:11:10 +0000]“GET / test HTTP / 1.1”200 988“ - ”“Mozilla / 5.0(Windows NT 6.1; WOW64; rv :32.0)Gecko / 20100101 Firefox / 32.0“

另一个证明:

将包含<?php phpinfo();的PHP文件上传到您的服务器上,并在生成的信息中使用#fragment_identifier ...访问它,该哈希值不会被提及一次。 因为对于服务器,它甚至不存在。

答案 2 :(得分:0)

正如@ luigi-belli所建议:应用encodeURIComponent()

或者,移动您的网址查询参数,以便进行如下调用:

$.ajaxSetup({ 
        scriptCharset: "iso-8859-1",
        contentType: 'Content-type: text/plain; charset=iso-8859-1',
        cache: true,
        data: { 'var1' : 'test#t', 'var2' : 'value2' }

        //zuerst alles encodieren, damit server keine fehler bekommt
        beforeSend: function(xhr, data) 
        {
            //wrong url
            console.log(data.url);
        }
    });

    //right url
    var link = "/example.php";
    $.get(link).done(function()
    {
        console.log("done");
    });

答案 3 :(得分:0)

#之后的字符被视为哈希,而不是查询字符串的一部分。您需要对特殊字符进行编码。您应该使用encodeURIComponent来完成它。

但好处是jQuery在get方法中内置了$ .param()方法,它将为你进行转换。

var link = "/example.php";
$.get(link, { "var1" : "tes#t", "var2" : "value2" }). done(...);
相关问题