javascript 使用 jQuery AJAX 加载 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19122428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:27:20  来源:igfitidea点击:

Load JSON Data Using jQuery AJAX

javascriptjqueryajaxjson

提问by Albert Viglieri

I need to print this information when clicking a button and sorting if by date, so far i have this: I have json file that looks like this, but I haven't been able to print it on the page and still haven't got to the sorting by date part. I am not sure if the problem is the link to the ajax version i am using or what is the problem, because i saw an example that looks just like this on youtube and it works just fine.

单击按钮并按日期排序时,我需要打印此信息,到目前为止我有这个: 我有看起来像这样的 json 文件,但我无法在页面上打印它,但仍然没有到按日期排序部分。我不确定问题是否出在我正在使用的 ajax 版本的链接上,或者是什么问题,因为我在 youtube 上看到了一个看起来像这样的例子,它工作得很好。

JSON:

JSON:

??[
{
    "users": [
        {
            "name": "user1",
            "Endorsement": "some comment",
            "date": "8/11/2012"
        },
        {
            "name": "user2",
            "Endorsement": "some comment2",
            "date": "9/27/11"
        },
        {
            "name": "user3",
            "Endorsement": "some comment3"
        },
        {
            "name": "user4",
            "Endorsement": "some comment4",
            "date": "4/2/13"
        },
        {
            "name": "user5",
            "Endorsement": "some comment5"
        },
        {
            "name": "user6",
            "Endorsement": "some comment6",
            "date": "3/17/13"
        },
        {
            "name": "user7",
            "Endorsement": "some comment7",
            "date": "5/22/13"
        },
        {
            "name": "user8",
            "Endorsement": "some comment8",
            "date": "9/27/13"
        }
    ]
}

]

]

HTML updated:

HTML 更新:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact</title>
    <link rel="shortcut icon" href="stridesFavicon.ico">
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="css/bootstrap-responsive.css">
    <link rel="shortcut icon" href='http://sites.google.com/site/lowcoupling/favicon_16x16.ico' />

</head>
<body>
    <!--Body content-->

  <div id='Div1'>


    <a href="#" id="clickme">Get JSON Data</a>


    </div>


    <script type="text/javascript"     src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>



    <script type="text/javascript" src="js/bootstrap.js"></script>
    <script src="myscript.js" type="text/javascript" /></script>
    <script type="text/javascript">

        $(document).ready(function () {
            $('.dropdown-toggle').dropdown();
        });  
    </script>
</body>
</html>

JS updated:

JS更新:

$("#clickme").click(function () {

$("#clickme").click(function () {

$.getJSON("users.json", function (data) {

    var items = [];
    $.each(data, function (key, dvalue) {


        $.each(dvalue, function (key, value) {
            items.push('<li id="' + key + '">' + value + '</li>');

        });
    });

    $('<ul/>', {
        'class': 'interest-list',
        html: items.join('')

    }).appendTo('body');

});

});

But is not working. meaning is not loading user names; instead it is printing something like this every time i click the link:

但不工作。意思是不加载用户名;相反,每次我单击链接时,它都会打印类似的内容:

?[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

?[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

回答by Labib Ismaiel

the jason is missing some commas, every line inside the json should end with a comma unless it is the last child in the scope, which makes it:

jason 缺少一些逗号,json 中的每一行都应该以逗号结尾,除非它是作用域中的最后一个孩子,这使得它:

[
    {
        "users": [
            {
                "name": "user1",
                "Endorsement": "some comment",
                "date": "8/11/2012"
            },
            {
                "name": "user2",
                "Endorsement": "some comment2",
                "date": "9/27/11"
            },
            {
                "name": "user3",
                "Endorsement": "some comment3"
            },
            {
                "name": "user4",
                "Endorsement": "some comment4",
                "date": "4/2/13"
            },
            {
                "name": "user5",
                "Endorsement": "some comment5"
            },
            {
                "name": "user6",
                "Endorsement": "some comment6",
                "date": "3/17/13"
            },
            {
                "name": "user7",
                "Endorsement": "some comment7",
                "date": "5/22/13"
            },
            {
                "name": "user8",
                "Endorsement": "some comment8",
                "date": "9/27/3"
            }
        ]
    }
]

回答by developerCK

try !

尝试 !

$("button").click(function () {

$.getJSON("users.json", function (obj) {


    $.each(obj.users, function (key, value) {
        $("ul").append("<li>" + value.name + "</li>");

    });

});

});

});

and if there is error then use debug console in browser. and either make a fiddle or write what is error. and there seems no ul element in your html.

如果出现错误,则在浏览器中使用调试控制台。要么做一个小提琴,要么写出什么是错误的。并且您的 html 中似乎没有 ul 元素。

回答by Rajesh

The json is not valid. I validated using http://jsonlint.com/and it says error at line 6. You left a comma in below part:

json 无效。我使用http://jsonlint.com/进行了验证,它在第 6 行显示错误。您在下面部分留下了一个逗号:

"Endorsement": "some comment"  
               "date":"8/11/2012"

This is the first endorsement-date pair

这是第一个背书日期对

回答by Niaz Morshed

$("button").click(function () {

$.getJSON("users.json", function (data) {



for (i in data)
{

for (k in data[i]) {
               alert(data[i][k]);
            }


});

});

回答by Niaz Morshed

$.ajax({
    type:'POST',
   url:'Default.aspx/GetPro',
  data:"{Pid:'"+ faram+"'}",
 contentType: 'application/json; charset=utf-8',
  dataType: 'json',
 async: true,
cache: false,

success: function(msg) {
 alert("{Pid:'"+ faram+"'}");
var orders =msg;
 if (orders.length > 0) {
test(orders);
   }
 else {
  alert("No Record Found");
   }
 },
error: function(xhr, textStatus, errorThrown) {
            alert(xhr.status);
              alert(errorThrown);
              alert(xhr.responseText);
        }

});

});

function test(data)
{

for (i in data)
          {
//ProductName Is Property Field Of c# Object
 alert(data[i]['ProductName'])
}



 }