新手问题:ajax与json如何从服务器上获取JSON数据?

我第一次写的AJAX与JSON方法,有点不懂怎么弄的呢,恳请各位老师帮忙说解,由于什么原因出错的?

<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(function () {
        $("button").click(function(){
            $.ajax({
                url:"http://www.tutorialspoint.com/json/data.json",
                type:"POST",
                dataType: "json",
                success:function(data){
                    $("#name").html(data.name);
                    $("#country").html(data.country);
                },
                error: function (err) {
                    console.log(err)
                }
            });
        })
    });
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body>
<h1>Cricketer Details</h1>
<table class="src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id="name">Sachin</div></td>
<td><div id="country">India</div></td></tr>
</table>
<div class="central">
<button type="button">Update Details </button>
</body>
</html>
阅读 6k
4 个回答

一万处错误,肯定无法执行,跟ajax无关,jq语法错误,html标签也不闭合,编辑器高亮,控制台弹错,很明显。

    $(function () {
        $("button").click(function(){
            $.ajax({
                url:"http://www.tutorialspoint.com/json/data.json",
                type:"POST",
                dataType: "json",
                success:function(data){
                    $("#name").html(data.name);
                    $("#country").html(data.country);
                },
                error: function (err) {
                    console.log(err)
                }
            });
        })
    });

看下控制台是否有报错信息,目前能看到的是成功回调写得有问题。

$("#name").html(data.name);
$("#country").html(data.country);

你回调函数里的jQuery方法 和原生DOM操作弄混了
应该是

success:function(data){
            $("#name").html(data.name);
            $("#country").html(data.country);
        }
    
    
这样写 你再试试看

1.(document) 前面少了个$, $(document).ready()...
2.click()未闭合
3.ready()未闭合 最后两个"}"分别加两个")"

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题