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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器