如何在json中包含一个php变量并将其传递给ajax [英] How to include a php variable in json and pass to ajax

查看:88
本文介绍了如何在json中包含一个php变量并将其传递给ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码

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. 我该如何解决?

The problem is: when I alert obj.result, it shows "$result", instead of showing Hello. How can I solve this?

推荐答案

示例的基本问题是$result用单引号引起来.因此,第一个解决方案是将其拆开,例如:

The basic problem with your example is that $result is wrapped in single-quotes. So the first solution is to unwrap it, eg:

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

但这还不够好,因为$result总是有可能包含一个"字符本身,导致例如{"result":""","count":3},它仍然是无效的json.解决方法是在$result插入json之前对其进行转义.

But this is still not "good enough", as it is always possible that $result could contain a " character itself, resulting in, for example, {"result":""","count":3}, which is still invalid json. The solution is to escape the $result before it is inserted into the json.

使用 json_encode() 函数,这实际上非常简单:

This is actually very straightforward, using the json_encode() function:

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

或者更好的是,我们可以让PHP通过传入整个数组而不只是$result来完成整个json编码本身:

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:

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

这篇关于如何在json中包含一个php变量并将其传递给ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆