javascript jQuery AJAX 将 url 作为字符串传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23837470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:39:16  来源:igfitidea点击:

jQuery AJAX pass url as string

javascriptphpjqueryajax

提问by 626

I have a ajax function that is passing a string of variables to my script but I have one variable that needs to contain a full url with parameters.

我有一个 ajax 函数,它将一串变量传递给我的脚本,但我有一个变量需要包含一个带参数的完整 url。

What happens is that var1 and var2 become $_POST variables but I need to save the whole url variable as a string.

发生的情况是 var1 和 var2 成为 $_POST 变量,但我需要将整个 url 变量保存为字符串。

var url = "http://domain.com/index.php?var1=blah&var2=blah";

var dataArray = "rooftop_id=" +rooftop_id+ "&url=" +url;

        $.ajax({
            type: "POST",
            url: "/scripts/error_check.php",
            data: dataArray,
            dataType: 'json'
        }); 

I would like my $_POST variable to look like this:

我希望我的 $_POST 变量看起来像这样:

$_POST['rooftop_id'] would be '1234'
$_POST['url'] would be 'http://domain.com/index.php?var1=blah&var2=blah'

Thanks in advance!

提前致谢!

回答by Danijel

Use encodeURIComponent()on url variable:

在 url 变量上使用encodeURIComponent()

var url = "http://domain.com/index.php?var1=blah&var2=blah";

var dataArray = "rooftop_id=1&url=" +encodeURIComponent(url);

$.ajax({
    type: "POST",
    url: "/scripts/error_check.php",
    data: dataArray,
    dataType: 'json'
}); 

回答by Quentin

Don't try to build your form data by hand. jQuery will encode it for you (with appropriate escaping) if you pass it an object.

不要尝试手动构建表单数据。如果您向它传递一个对象,jQuery 将为您编码(使用适当的转义)。

var url = "http://domain.com/index.php?var1=blah&var2=blah";

$.ajax({
    type: "POST",
    url: "/scripts/error_check.php",
    data: { url: url, rooftop_id: rooftop_id },
    dataType: 'json'
});