通过 Ajax 调取后台接口将返回的 json 数据绑定在页面上

第一步:

  编写基础的 html 框架内容,并引入 jquery:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>测试Ajax</title>
        <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
        <script>
            
        </script>
    </head>
    <body>
        
    </body>
</html>

第二步:

  在 “<body></body>” 中间插入要点击的按钮和用来显示数据的<p>标签,并编写对应的 function:

    <body>
        <button id="btn">点击获取数据</button>
        <p id="ganmao"></p>
    </body>

  function:

        <script>
        $(function(){
            $("#btn").on("click", function(){
                //调用 ajax
            });
        })
        </script>

第三步:

  使用 ajax 调用后台接口并处理数据:

                $.ajax({
                    url: ‘http://localhost:53087/test/ajax‘,    //后端程序的url地址
                    type: ‘get‘,
                    dataType: ‘json‘,
                    data:{    //发送给服务器的数据,如果是get请求,也可以写在url地址的?后面
                        "city":‘郑州‘,
                    }
                })
                .done(function(resp){        //请求成功以后的操作(resp是后端返回的json数据,值为:{"city":"郑州"})
                    console.log(resp);
                    var data = eval(‘(‘ + resp + ‘)‘);        //data为json数据转换成的对象,值为:{city: "郑州"}
                    console.log(data);
                    var city = data[‘city‘];
                    console.log(city);
                    
                    $(‘#ganmao‘).html(city)
                })
                .fail(function(error){        //请求失败以后的操作
                    console.log(error);
                });

合在一起的代码:


<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>测试Ajax</title>
        <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
        <script>
        $(function(){
            $("#btn").on("click", function(){
                $.ajax({
                    //后端程序的url地址
                    url: http://localhost:53087/test/ajax,
                    type: get,
                    dataType: json,
                    data:{    //发送给服务器的数据,如果是get请求,也可以写在url地址的?后面
                        "city":郑州,
                    }
                })
                .done(function(resp){        //请求成功以后的操作
                    console.log(resp);
                    var data = eval(( + resp + ));
                    console.log(data);
                    var city = data[city];
                    console.log(city);
                    
                    $(#ganmao).html(city)
                })
                .fail(function(error){        //请求失败以后的操作
                    console.log(error);
                });
            });
        })
        </script>
    </head>
    <body>
        <button id="btn">点击获取数据</button>
        <p id="ganmao"></p>
    </body>
</html>

View Code

运行效果: