在 JavaScript 中解码 URL 时遇到问题


trouble decoding url in javascript

我正在使用php对url字符串进行编码,然后通过curl将其传递给phantomjs脚本,我正在尝试使用javascript对其进行解码。

我从:

localhost:7788/hi there/how are you/

它变成了:

 localhost:7788/hi+there%2Fhow+are+you

在 PHP 端由 urlencode() 函数。

在幻影方面,我有:

// Create serever and listen port 
server.listen(port, function(request, response) {    
function urldecode(str) {
   return decodeURIComponent((str+'').replace(/'+/g, '%20'));
}    

        // Print some information Just for debbug 
        console.log("We got some requset !!!"); 
        console.log("request method: ", request.method);  // request.method POST or GET 
        console.log("Get params: ", request.url); //     
           url= urldecode(request.url);
        //-- Split requested params
      var requestparams = request.url.split('/');    

      console.log(urldecode(requestparams[1]));
      console.log(urldecode(requestparams[2]));

控制台上的输出是:

.....
request method:  GET
Get params:  /hi%2Bthere/how%2Bare%2Byou
hi+there
how+are+you

为什么"+"号没有替换为空格?我正在尝试摆脱它们,在我看来,函数"urldecode"应该这样做。

你应该

在PHP端使用rawurlencode()而不是urlencode(),所以空格是用%20而不是+符号编码的,所以javascript可以用decodeURIComponent()很好地解码它们。