如何使用AJAX将php变量放入JSON?

时间:2017-03-11 23:06:56

标签: javascript php json ajax

我正在尝试发回一个JSON OBJECT,但是数据依赖于在提交AJAX调用时发送的$ id变量,我如何在我的JSON字符串中使用这个$ id变量并将其发送回JSON。解析()?

这基本上就是我想要做的,我是JSON的新手

我希望如何

$id = somenumber;
echo '{"imageSrc":"assets/img/ . $id . .jpg","second":"radi"}';

发送到JSON.parse()时应该如何

 echo '{"imageSrc":"assets/img/2.jpg","second":"radi"}';

但是我只能在JSON中添加一个变量或除纯文本以外的任何其他内容吗?

AJAX get请求的当前页面 PHP

require_once '../includes/db.php';
require_once '../includes/functions.php';

$dbCon = dbCon();
define("SQL", "SELECT * FROM rating ORDER BY rand() LIMIT 1");
$result = $dbCon->query(SQL);

while ($row = $result->fetch_object()) {
    $id = $row->id;

    //HOW DO I PARSE A VARIABLE INTO THIS JSON STRING BEFORE AJAX GETS IT??
    echo '{"imageSrc":"assets/img/2.jpg","second":"radi"}';
}

编辑:json_encode()是一个php函数,感谢axiac感谢信息

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>
The above example will output:

{"a":1,"b":2,"c":3,"d":4,"e":5}

1 个答案:

答案 0 :(得分:0)

while ($row = $result->fetch_object()) {
$id = $row->id;

//in this way
echo '{"imageSrc":"assets/img/'.$id.'.jpg","second":"radi"}';

}

当你把它放在单引号

时,php不会替换变量值
$var = "some text";
echo 'hi $var'; //output : hi $var
echo "hi $var"; //output : hi some text

或者您可以将数据放入数组中并将其转换为json,如此

$arr = ["imageSrc"=>"assets/img/".$id.".jpg","second"=>"radi"];
echo json_encode($arr);