2011-05-19 64 views
1

有沒有解決方案來防止json_encode添加轉義字符?我從ajax請求返回一個json obj。防止json_encode添加轉義字符

這是我目前有:

foreach ($files as $file) 
{ 
    $inf = getimagesize($file); 

    $farr[] = array (
        "imgurl" => "/".str_replace("\\" , "/" , str_replace(DOCROOT , "" , $file)) , 
        "width"  => $inf[0] , 
        "height" => $inf[1] 
        ); 
} 
$t = json_encode($farr); 

它提供:

[ 
{\"imgurl\":\"\\\/_assets\\\/portfolio\\\/96\\\/full.png\",\"width\":580,\"height\":384}, 
{\"imgurl\":\"\\\/_assets\\\/portfolio\\\/95\\\/full.png\",\"width\":580,\"height\":452}, 
{\"imgurl\":\"\\\/_assets\\\/portfolio\\\/94\\\/full.png\",\"width\":580,\"height\":384} 
] 

,但我需要:具有援引導致了該imgUrl的寬度和高度指標

[ 
{imgurl:"/_assets/portfolio/96/full.png",width:580,height:384}, 
{imgurl:"/_assets/portfolio/95/full.png",width:580,height:452}, 
{imgurl:"/_assets/portfolio/94/full.png",width:580,height:384} 
] 

休息我的JavaScript打破

運氣不好,所以任何提示非常歡迎...

+3

'json_encode()'做的是正確的事情。這意味着你一定在做錯事。請顯示打破的代碼。 – Tomalak 2011-05-19 15:23:53

+0

你爲什麼要這樣? – 2011-05-19 15:24:36

+0

你想要的輸出是一個Javascript表達式,而不是JSON序列化。然而,在你的輸出中有太多的addslashes,json_encode不會這樣做。 – mario 2011-05-19 15:31:09

回答

3

使用你在你的問題,並var_dumping它有代碼,我得到如下:string(40) "[{"imgurl":"\/bla"},{"imgurl":"\/blub"}]"

只有當我加倍json_encode像$t = json_encode(json_encode($farr));我得到與你一樣的結果 - 所以必須有第二個json_encode ...

+1

D'oh - 在返回的方法中編碼導致ajaxs腳本inturn json_encodes結果....如果一個橡皮鴨調試一個 - srry窺視...; P – 2011-05-19 15:39:39

+0

必不可少的部分「只有當我加倍json_encode」 – ceph3us 2017-08-05 05:12:40