2012-09-19 17 views
3

我的代碼如何包含在JSON PHP變量,並傳遞給阿賈克斯

var json = xmlhttp.responseText; //ajax response from my php file 
obj = JSON.parse(json); 
alert(obj.result); 

而在我的PHP代碼

$result = 'Hello'; 

echo '{ 
     "result":"$result", 
     "count":3 
     }'; 

的問題是:當我提醒obj.result,它顯示"$result",而不是顯示Hello。 我該如何解決這個問題?

回答

10

你的榜樣最根本的問題是,$result被包裹在單引號。因此,第一個解決方案是解開它,比如:

$result = 'Hello'; 
echo '{ 
    "result":"'.$result.'", 
    "count":3 
}'; 

但這仍然不是「足夠好」,因爲它始終是可能的$result可能包含"人物本身,導致,例如,{"result":""","count":3},這仍然是無效的json。解決方案是在將其插入到json中之前將其脫離$result

這其實很簡單,使用json_encode()功能:

$result = 'Hello'; 
echo '{ 
    "result":'.json_encode($result).', 
    "count":3 
}'; 

,或者甚至更好,我們可以有PHP做的JSON編碼本身的整體,通過傳遞整個陣列中,而不是僅僅$result

$result = 'Hello'; 
echo json_encode(array(
    'result' => $result, 
    'count' => 3 
)); 
2

您使用單引號在你的迴音,因此沒有字符串插值發生

使用json_encode()

$arr = array(
    "result" => $result, 
    "count" => 3 
); 
echo json_encode($arr); 

作爲獎勵,json_encode將正確編碼您的回覆!

+0

我也試過這個。但它顯示了相同的 echo'{0}結果「:''。$ result。'」, 「count」:3 }'; – Nevin

+0

所有** UTF-8 **字符串。 –

+0

Nevin,使用'json_encode' –

0

嘗試:

$result = 'Hello'; 
echo '{ 
    "result":"'.$result.'", 
    "count":3 
}'; 
4

您應該使用json_encode正確的數據進行編碼:

$data = array(
    "result" => $result, 
    "count" => 3 
); 
echo json_encode($data); 
0
$result = 'Hello'; 

$json_array=array(
    "result"=>$result, 
    "count"=>3 
) 
echo json_encode($json_array); 

這就是全部。