Php 如何从json中获取值并访问它

Php 如何从json中获取值并访问它,php,jquery,ajax,json,Php,Jquery,Ajax,Json,这就是我使用ajax的方式 $.get('checkanswer.php',{'clickedvalue':clickedvalue,'qid':qid},function(data){ $this.find(".report").html(data); 这是我的PHP代码,数据来自这里 <?php $countresult=0; $questionid=$_GET['qid']; $answer=$_GET['clickedvalue']; $dbcon

这就是我使用ajax的方式

$.get('checkanswer.php',{'clickedvalue':clickedvalue,'qid':qid},function(data){
                $this.find(".report").html(data);
这是我的PHP代码,数据来自这里

<?php
$countresult=0;
$questionid=$_GET['qid'];
$answer=$_GET['clickedvalue'];
$dbconnect=mysqli_connect('localhost','root','','quiz')or die("Error Connecting to database");
$query="select answer from question_answer where id=$questionid";
    $result=mysqli_query($dbconnect,$query);
    while($rows=mysqli_fetch_array($result))
    {
        $dbanswer=$rows['answer'];
    }
    if($dbanswer==$answer)
        {
        echo "Correct";
        $countresult=$countresult+1;
        }
    else{
        echo "Incorrect";
        $countresult=$countresult-1;
    }   

?>

之前我只是检查结果是否正确并显示结果,但现在我希望PHP页面返回存储在$countresult中的计数的变量。我知道我必须使用json,但如何在PHP页面中使用它,传递值并从另一个页面访问该值,在PHP中:

$data = array('countresult' => $countresult);
$str = json_encode($data);
echo $str;
在您的js中:

$.get('checkanswer.php',{'clickedvalue':clickedvalue,'qid':qid},function(data){
       alert(data['countresult']);
}, "json");
关于在php中使用json_编码的文档

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

 echo json_encode($arr);
 ?>

通常将消息放入数组:

$server_response['error'] = "something";
$server_response['Success'] = "some other thing";
$sever_response['vars'] = "blah blah";
echo json_encode($server_response);
然后,如果您的响应变量是ServerResponse,那么可以从js访问

ServerResponse.error or
ServerResponse.Success or
ServerResponse.vars

当我提醒数据数组值显示未定义的值时,我为稍后回复您的评论而担心什么,我正在出差。我更新了答案,
jQuery.get()
应该指示来自服务器的数据类型。我们在这里使用json数据格式。