如何使用jquery ajax和jsonp在您自己的域上读取json数据

How to read json data on your own domain using jquery ajax and jsonp

本文关键字:自己的 读取 数据 json jquery 何使用 ajax jsonp      更新时间:2023-09-26

我有这段代码,我想读取我域上的JSON数据,但我已经尝试了所有我能想到的,但无法获得。

这是代码:

<script>
    $(function () {
        $.ajax({
            "url": "http://www.mmsbip.com.ng/accounts.json",
            "type": "get",
            "dataType": "json"
        })
        .done(function (data) {
            var options = $("#users");
            $.each(data, function (val) {
                   alert(data.UserID);   
                }));
            });
        })
        .fail(function (jqXHR, status, error) {
            console.log("status:", status, "error:", error);
        })
    });

我的服务器上accounts.json中的数据是

[
{
    "UserID": "timotech",
    "UserName": "timotech@yahoo.com",
    "Password": "password"
},
{
    "UserID": "teslim",
    "UserName": "teslimbakare@live.com",
    "Password": "password"
},
{
    "UserID": "bola",
    "UserName": "bettyolabode@yahoo.com",
    "Password": "password"
}

]

如何从服务器获取这些数据

编辑:我决定把整页都贴出来,这样你就可以看到我犯了什么错误。感谢

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Simple JSON Example</title>
    <script src="jmobile/jquery-2.1.3.js"></script>
    <script>
        $(function () {
            $.ajax({
                "url": "http://www.mmsbip.com.ng/accounts.json",
                "type": "get",
                "dataType": "json"
            })
        .done(function (data) {
            var options = $("#users");
            $.each(data, function (val) {
                alert(data.UserID);
            });
        })
        .fail(function (jqXHR, status, error) {
            console.log("status:", status, "error:", error);
        })
        });
</script>
</head>
<body>
    <h2>Simple JSON Example</h2>
    <p>This DropDown is populated using $.ajax()</p>
     <select name="users" id="users" />
</body>
</html>

该警报只是为了测试是否返回json数据。感谢

代码中有几个小错误。试试这个:

    $(function () {
        $.ajax({
            "url": "http://www.mmsbip.com.ng/accounts.json",
            "type": "get",
           "dataType": "json"
     })
    .done(function (data) {
        var options = $("#users");
        $.each(data, function (val) {
           alert(data.UserID);   
        });
    })
    .fail(function (jqXHR, status, error) {
       console.log("status:", status, "error:", error);
    })
});

您过早地(在警报之后)关闭了原始函数,并且代码中有一个额外的});