在html页面中显示JSON响应

时间:2018-05-23 11:30:18

标签: javascript json

我有一个生成JSON类型数据的php文件:

    header('Content-type: application/json');

    if($_POST["id"] == 1){
        $arr = array(
            'firstname' => "John",
            'lastname' => "Doe"
        );
        echo json_encode($arr);
    }

我想使用JQuery AJAX在html页面中显示响应:

$(document).ready(function(){
    $.ajax({
        url: "http://apk.vitka.ir/apk-api/",
        type: "POST",
        dataType: "json",
        data: "id=1",
        success: function(data){
            var person = jQuery.parseJSON(data);
            console.log(person.name);
        },
        error: function(error){
            console.log("Error:");
            console.log(error);
        }
    });
});

我的代码有什么问题以及我如何纠正这个问题? 然后我想在页面中的html模板中显示resaults:

<div class="someclass">First Name Is : John</div>
<div class="someclass">Last Name Is : Doe</div>

我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

您的问题似乎有点半生不熟,但如果您想要HTML中的名字和姓氏,那么您需要容器:

<div class="someclass">First Name Is : <span id="firstName"></span></div>
<div class="someclass">Last Name Is : <span id="lastName"></span></div>

$(document).ready(function(){
    $.ajax({
        url: "http://apk.vitka.ir/apk-api/",
        type: "POST",
        dataType: "json",
        data: "id=1",
        success: function(data){
            var person = jQuery.parseJSON(data);
            $('#firstName').text(person[0].firstName);
            $('#lastName').text(person[0].lastname);
        },
        error: function(error){
            console.log("Error:");
            console.log(error);
        }
    });
});

答案 1 :(得分:0)

我发现了问题: 数据变量已经是解析对象,不需要再次解析:)