My Code
var json = xmlhttp.responseText; //ajax response from my php file
obj = JSON.parse(json);
alert(obj.result);
And in my php code
$result = 'Hello';
echo '{
"result":"$result",
"count":3
}';
The problem is: when I alert obj.result, it shows "$result", instead of showing Hello.
How can I solve this?
The basic problem with your example is that
$resultis wrapped in single-quotes. So the first solution is to unwrap it, eg:But this is still not “good enough”, as it is always possible that
$resultcould contain a"character itself, resulting in, for example,{"result":""","count":3}, which is still invalid json. The solution is to escape the$resultbefore it is inserted into the json.This is actually very straightforward, using the
json_encode()function:or, even better, we can have PHP do the entirety of the json encoding itself, by passing in a whole array instead of just
$result: