使用json_encode ajax响应作为jquery变量

时间:2014-02-16 17:35:19

标签: javascript php jquery ajax json

我将来自ajax流程页面的数据作为

传递
<?php
       header('Content-Type: application/json; charset=utf-8');
       $response = array("username" => "alpha", "message" => 'Passed.', "divid" => 5);
       echo json_encode($response);
?>

在源页面中,我需要收集divid以在相应的div中显示用户名和消息

success:function(data) 
    {
var obj = $.parseJSON(data);    
    var k = obj[0].divid;
    $('....calling_by_id according to value of k..').html(data.username);
    $('calling_by_id  according to value of k').html(data.message);
    $('.success').fadeIn(200).show();
}

2 个答案:

答案 0 :(得分:1)

试试这个

var k = data.id; //As pointed out by dfsq thanks to him
$('#' + k).html(data.validation);

答案 1 :(得分:0)

您不需要自己解析JSON,jQuery足够聪明,可以在场景后面执行:

success: function(data) {
    var k = data.divid;
    ...
}