javascript 如何在json中包含一个php变量并传递给ajax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12488784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:18:18  来源:igfitidea点击:

How to include a php variable in json and pass to ajax

phpjavascriptajaxjson

提问by Nevin

My Code

我的代码

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

And in my php code

在我的 php 代码中

 $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?

问题是:当我 alert 时obj.result,它显示"$result",而不是显示Hello。我该如何解决这个问题?

回答by Will Palmer

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

您的示例的基本问题$result是用单引号括起来。所以第一个解决方案是打开它,例如:

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

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.

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

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

这其实很简单,使用json_encode()函数:

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

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:

或者,更好的是,我们可以让 PHP 自己完成整个 json 编码,方法是传入一个完整的数组,而不仅仅是$result

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

回答by Gumbo

You should use json_encodeto encode the data properly:

您应该使用json_encode正确编码数据:

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

回答by ma?ek

You're using single quotes in your echo, therefore no string interpolation is happening

您在回声中使用单引号,因此没有发生字符串插值

use json_encode()

使用json_encode()

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

As a bonus, json_encodewill properly encode your response!

作为奖励,json_encode将正确编码您的回复!

回答by seangates

Try:

尝试:

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

回答by ZloyPotroh

$result = 'Hello';

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

That's all.

就这样。