使用Ajax獲取本地json數據


一、使用原生ajax獲取本地JSON文件中的數據

1)創建json數據文件,文件名:demo.json

text.json內的數據代碼如下:

{
"person":{"name":"tom","age":18}
}

2)HTML文檔中的代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index</title>
</head>
<body>
    <script>
        var xhr="";//聲明變量容納XMLHttpRequest對象
        //封裝XMLHttpRequest對象創建方法(用於兼容低版本IE瀏覽器)
        function createXHR(){
            if(new window.XMLHttpRequest){//如果瀏覽器支持對象XMLHttpRequest
                xhr=new XMLHttpRequest();
            }else{
                xhr=new ActiveXObject("Microsoft.XMLH");//低版本IE使用ActiveXObject
            }
        }
        createXHR();//調用函數以創建XMLHttpRequest對象

        //使用XMLHttpRequest對象發送請求
        xhr.open("get","./demo.json",false);//創建請求
        xhr.send(null);//發送請求

        //獲取返回的json數據,
        var personStr=xhr.responseText;//返回的數據都是字符串,不具備對象方法
        var per=JSON.parse(personStr);//使用JSON.parse方法將字符串數據轉換為javascript對象
        console.log(per.person.name)//tom
    </script>
</body>
</html>

二、使用Ajax獲取本地json文件中的數據(注:使用jquery獲取json中的數據,不需要再使用JSON.parse()將數據轉為javascript對象)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
</head>
<body>
    <script>
        $(document).ready(function(){
            $.ajax({
                type: "get",//請求類型
                datatype: "json",//數據類型
                url: "./demo.json",//向哪里請求
                success: function(data){//請求成功后執行該函數
                    console.log(data.person.name)//tom
                }
            })
        })
    </script>
</body>
</html>

另、獲取HTML文檔內部的JSON數據

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index</title>
</head>
<body>
    <script>
        var jsonData='{"name": "tom","age": 18}';//創建json數據
        var per=JSON.parse(jsonData);//將json數據轉換為javascript對象
        console.log(per.name)//tom
    </script>
</body>
</html>

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM