1. 程式人生 > >ajax-處理json返回值

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字串+')')