ajax-处理json返回值

<body>
    <input type="button" name="" value="换一首">
    <h1>名称</h1>
    <h5>作者</h5>
    <p>内容</p>
</body>
<script type="text/javascript">
    var a = $('input[type="button"]')[0];
    
    $('input[type="button"]')[0].onclick = function(){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(this.readyState == 4){
                //json格式转成对象格式
                var res = eval('(' +this.responseText+ ')');
                $('h1').html(res.title);
                $('h5').html(res.author);
                $('p').html(res.content);
            }
        }
        xhr.open('get', 'tangshi', true);
        xhr.send(null);
    };
</script>

总结:
json转对象的方式:eval('('+json字符串+')')

猜你喜欢

转载自blog.csdn.net/Wake_me_Up123/article/details/83987350