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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c