dqysi86208 2016-05-16 14:58
浏览 66
已采纳

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

Following are my code i want to retrieve values from JSON which is returned by php file. following are my php code.

$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'],
       "answer_id_$i"=>$value['answer_id'],
       "ans_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();

Following are my javascript code.

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);

            }
            );

}

following are my result.

[{"question_id_1":"2","answer_id_1":"3","ans_tags_1":"","test_attempt_1":"181"},{"question_id_2":"1","answer_id_2":"1","ans_tags_2":"This is a tag test","test_attempt_2":"181"}]

How can i retrive values.

  • 写回答

1条回答 默认 最新

  • doucang5542 2016-05-16 15:07
    关注

    You can simply parse the JSON in Javascript:

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

    Then you can simply access the data stored in obj:

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

    EDIT (thanks to Webomatik):

    Of course you have to have to pay attention to your result. In your case your result is an array, so you could access the single objects in the array via

    obj[0].question_id_1 // "2"
    obj[0].answer_id_1 // "3"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?