如何从php返回的JSON中检索值


How to retrive values from JSON returned by php

以下是我想要从php文件返回的JSON中检索值的代码。以下是我的php代码。

$i=1;
foreach($chck as $value){
$qry_a = "SELECT ans_tags FROM wp_pp_actionphp_answers where id=".$value['answer_id'];
$result_a = $wpdb->get_results( $qry_a );  
$final[]=array(
       "question_id_$i"=>$value['question_id'],
       "answerswer_id_$i"=>$value['answer_id'],
       "answers_tags_$i"=>$result_a[0]->ans_tags,
       "test_attempt_$i"=>$test_count_by_email,
       );
       $i++;
   }
$jsonstring = json_encode($final);
print_r($jsonstring);//Return JSON to javascript file
exit();

以下是我的javascript代码。

function get_result(result_id,email){
var data='result_id=' + result_id+"&email="+email;
            $.post(
            ajaxurl + '?action=actionphp_get_result',
            data,
            function(result){
                document.write(result);
            }
            );

}

以下是我的结果。

[{"question_id_1":"2","answerswer_id_1":"3","answers_tags_1":"","test_attempt_1":"181"},{"question_id_2":"1","answerswer_id_2":"1","answers_tags_2":"This is a tag test","test_attempt_2":"181"}]

我如何检索值。

您可以简单地在Javascript中解析JSON:

var data = "{'"a'": 1, '"b'": 2, '"c'": [1,2,3]}"; // your result
var obj = JSON.parse(data);

然后您可以简单地访问存储在obj:中的数据

obj.a -> 1
obj.b -> 2
obj.c[0] -> 1

编辑(感谢Webomatik):

当然,你必须注意你的结果。在您的情况下,结果是一个数组,因此您可以通过访问数组中的单个对象

obj[0].question_id_1 // "2"
obj[0].answer_id_1 // "3"