使用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>

  

  

原文地址:https://www.cnblogs.com/vinson-blog/p/12952094.html