drlnsli18864734
2014-05-23 19:57 阅读 127

jQuery AJAX将url作为字符串传递

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.

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

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['rooftop_id'] would be '1234'
$_POST['url'] would be 'http://domain.com/index.php?var1=blah&var2=blah'

Thanks in advance!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • donglao7947 donglao7947 2014-05-23 20:36

    Use encodeURIComponent() on url variable:

    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'
    }); 
    
    点赞 评论 复制链接分享
  • dpf5207 dpf5207 2014-05-23 20:43

    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.

    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'
    }); 
    
    点赞 评论 复制链接分享

相关推荐