Jquery$.get在标签后剪切url

Jquery $.get cuts url after hashtag

本文关键字:url 标签 get Jquery      更新时间:2023-09-26

我正在尝试向服务器发送一个带有标签的url,比如

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

如果我在beforeSend函数中跟踪url,我会发现url只是

/example.php?var1=tes

以及删除标签和包含标签之后的所有内容。如果我在使用$.get()函数之前将标签编码为%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(包括标签)。

将encodeURIComponent()应用于URL字符串

URL无效/格式错误。

标签必须是URL的最后一部分

标签不是HTTP请求的的一部分,因此不能在其中。

你不能把标签放在URL的中间,只有一种模式:

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/

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

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

[26/Sep/2014:11:10+0000]"GET/testHTTP/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访问它。。。在生成的信息中,散列值一次也没有被提及因为对于服务器来说,它根本不存在

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

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

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

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

或者移动您的URL查询参数以进行这样的调用:

$.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");
    });