【问题标题】:decodeURIComponent(uri) is not working?decodeURIComponent(uri) 不工作?
【发布时间】:2011-05-19 03:38:57
【问题描述】:

我正在使用 Ajax 发布内容,并且我正在使用 http.send(encodeURIComponent(params)); 进行编码……但我无法在 PHP 中对其进行解码。我正在使用 POST,所以我认为它不需要编码?我很困惑我应该如何解码 PHP 中的值...

params = "guid="+szguid+"&username="+szusername+"&password="+szpassword+"&ip="+ip+"&name="+name+"&os="+os;
        //alert(params);
        document.body.style.cursor = 'wait';//change cursor to wait

        if(!http)
            http = CreateObject();  

        nocache = Math.random();

        http.open('post', 'addvm.php');
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", params.length);
        http.setRequestHeader("Connection", "close");
        http.onreadystatechange = SaveReply;
       http.send(encodeURIComponent(params));

【问题讨论】:

    标签: php javascript ajax urlencode encodeuricomponent


    【解决方案1】:

    encodeURIComponent 将对所有分隔键/值对的 &s 和 =s 进行编码。您需要在每个部分单独使用它。像这样:

     params = 
     "guid="      + encodeURIComponent(szguid)     + 
     "&username=" + encodeURIComponent(szusername) +
     "&password=" + encodeURIComponent(szpassword) +
     "&ip="       + encodeURIComponent(ip)         +
     "&name="     + encodeURIComponent(name)       +
     "&os="       + encodeURIComponent(os);
        //alert(params);
        document.body.style.cursor = 'wait';//change cursor to wait
    
        if(!http)
            http = CreateObject();  
    
        nocache = Math.random();
    
        http.open('post', 'addvm.php');
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", params.length);
        http.setRequestHeader("Connection", "close");
        http.onreadystatechange = SaveReply;
        http.send(params);
    

    【讨论】:

    • 不,你没有。您想在 JavaScript 中执行此操作。在 PHP 中做这件事是不必要的困难和毫无意义。
    • @minitech: okies :) 但如何?就像我使用 $username = trim($_POST["username"]); $password = $_POST["密码"]; $ip = 修剪($_POST["ip"]); $name = trim($_POST["name"]); $os = 修剪($_POST["os"]); $hostid = "物理";在 php 中如何解码它们...之后我的所有字段都可以使用 + 和 & 字符串?
    • @Stan:好的,不!不要在 PHP 中对它们进行解码。让我说清楚:您在 JavaScript 中发送的值不正确。您不能只在所有参数上使用encodeURIComponent,您必须单独使用它们。
    • @minitech: 好的,但我怎么能单独发送它?以编码形式,我想你是对的,我在编码方面犯了一些错误
    • @Stan:请参阅我编辑的帖子,了解您应该如何对组件进行编码。
    【解决方案2】:

    如果您从 JS 提交编码值并希望在 PHP 中 decode 它们,您可以执行以下操作:

    // decode POST values so you don't have to decode each pieces one by one
    $_POST = array_map(function($param) {
                return urldecode($param);
            }, $_POST);
    
    // assign post values after every value is decoded
    

    【讨论】:

    • 我可以使用 $_GET(将所有 $_POST 替换为 $_GET 来代替上面的脚本)吗??
    • @bungdito codewise 是的,但这不是一个好习惯。我也看不出你需要这样做的理由。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多