jQuery serialize将URL序列化错误

时间:2011-07-06 11:05:01

标签: php jquery encoding urlencode

我有一个表单,我提交并使用.serialize来帮助我从表单中收集所有数据。现在,我已经检查了firebug在POST中发送了什么,我可以看到一个很好的格式化字符串,例如

index.php?data=sth&data2=sth

但问题在于此&在PHP中 - PHP输出如下:

index.php?data=sth& a m p ;data2=sth

看到这个放大器?好吧,它写的没有空格,它编码(我在谷歌发现)版本的&amp ;.那么,我该怎么做才能在数据库中正确输入这个url然后获取它并在网站上显示它而不用这个&放大器; ?

编辑:如果有可能我想要一个带有&的字符串将该格式放入DB。 (所以,带& sign)。

编辑#2: 我如何发送数据:

 var formData = $("#myForm :input[value]").serialize();
 $.ajax({
     type: 'POST',                    
     cache:false,
     url: '_ajax/updateGameInfo.php', 
     async: false,                     
     dataType: 'text',
     data: allData,
     success: function(jsonObj) { 
         if (jsonObj){                       
             $msg = 'Data sucessfully updated! Reloading page...';
             alert($msg);
         }
         else{
             $msg = 'Error with the update!';
             alert($msg);
         }   
     }
 });    

这是我的updateGameInfo.php:

$gameRepos = new GameRepository();    

$game = $gameRepos->updateGame();
echo json_encode( $game );   

如果你也喜欢,这里是来自GameRepository的updateGame函数:

public function updateGame()
{
    $cleanPost = array_map( array('GameRepository', 'cleanPostData'), $_POST);
    $attributes = array_keys($cleanPost);
    $values = array_values($cleanPost);      

    $table = $this->resolveTableName( $cleanPost["selectedTypeId"] );
    $id = $cleanPost["selectedGameId"];

    if ($this->openConnection())
    {                                                
        $pairs = "";
        foreach ($cleanPost as $attribute => $value){
            if ($attribute != "selectedGameId" && $attribute != "selectedTypeId"){

            if ($attribute == "url")
                $value = str_replace("amp;", "", $value);    

                $pairs .= $attribute . "='" . $value . "',";
            }    
        }

        $pairs = rtrim($pairs, ','); //remove last comma

        $query = "UPDATE $table SET $pairs WHERE id=$id;";

        $result = pg_query($query);
        if (!$result){
            mysql_error());
            return false;
        }                
        else 
            return true;
    }
    else
        return false;
}

2 个答案:

答案 0 :(得分:2)

如果您将URL作为POST变量传递,那么PHP将自动编码任何特殊字符。因此,假设POST变量名称为url,您可能希望在其他所有内容之前在您的php脚本中执行此操作:

$_POST['page_url'] = htmlspecialchars_decode($_POST['page_url']);

问题不在于jquery,而在于php。传递json字符串时会遇到类似的问题。

答案 1 :(得分:0)

您是否检查了页面的html标题中的字符集? 试着改变它!