【问题标题】:how to send a url using Javascript ajax? [duplicate]如何使用 Javascript ajax 发送 url? [复制]
【发布时间】:2012-12-21 16:19:06
【问题描述】:

可能重复:
How to encode a URL in JavaScript?

我正在尝试使用以下代码将 url 发送到 php 代码,但由于 url 包含 &a=12&b=4 一旦我在我的 php 代码中获得“a”变量的值,地址的最后一部分就会被删除。

网址 = http://www.example.com/help.jpg?x=10&a=12&b=4 但是我在我的php文件中得到的url是http://www.example.com/help.jpg?x=10(&a=12&b=4被删除了,我知道原因是javascript,ajax将它与url地址混淆了,不知道它只是一个值但不知道知道怎么解决)

         function upload(url){

            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("output").innerHTML= xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET","Photos.php?a="+url,true);
            xmlhttp.send();
     }        


   if(isset($_GET["a"]))
   {
       $Address = $_GET["a"];
       echo $Address;

   }

输出是 >>> "http://www.example.com/help.jpg?x=10" 但它应该是 http://www.example.com/help.jpg?x=10&a=12&b=4

【问题讨论】:

  • @gd1 哇,真是个有趣的巧合。
  • 作为评论,我想说,如果您要发布一些内容,您应该使用 POST http 方法,而不是 GET。考虑到您的 url 问题,我猜该解决方案依赖于在 php 中使用 javascript url_encode 方法和 $_REQUEST 数组。

标签: php javascript ajax


【解决方案1】:

你需要对参数进行编码

xmlhttp.open("GET","Photos.php?a="+encodeURIComponent(url),true);

【讨论】:

    【解决方案2】:

    您需要对 URL 进行编码。您可以像这样使用 encodeURIComponent(str) 和 encodeURI(str):

    var eurl = encodeURIComponent("http://www.example.com/help.jpg?x=10&a=12&b=4");
    xmlhttp.open("GET","Photos.php?a=" + eurl, true);
    

    【讨论】:

      猜你喜欢
      • 2016-10-21
      • 1970-01-01
      • 2021-12-05
      • 2021-10-23
      • 1970-01-01
      • 2012-08-24
      • 2017-01-26
      • 2015-11-20
      • 2016-05-18
      相关资源
      最近更新 更多