decodeURIComponent(uri)不工作?

时间:2011-05-19 03:38:58

标签: php javascript ajax urlencode encodeuricomponent

我正在使用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));

2 个答案:

答案 0 :(得分:3)

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);

答案 1 :(得分:1)

如果您要从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