在 jQuery 中调用 AJAX 函数后如何使用 JSON 数据

发布于 2024-11-10 17:25:02 字数 676 浏览 0 评论 0原文

使用此代码:

 $("#mybutton").click(function(){
           $.ajax({
                url: '/Member/GetPinPoints/@Model.Id',
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function(data) {
            alert(data);
            },
            error: function() {

            alert("error");
            }
            });


    return false;
});

我收到一个如下所示的 JSON 对象:

[{"Position":1,"Top":182,"Left":20,"Height":73,"Width":90},{"Position":2,"Top":69,"Left":103,"Height":98,"Width":1}]

如何迭代此数据,假设我是否想提醒每个单独的值?

With this code:

 $("#mybutton").click(function(){
           $.ajax({
                url: '/Member/GetPinPoints/@Model.Id',
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function(data) {
            alert(data);
            },
            error: function() {

            alert("error");
            }
            });


    return false;
});

I am receiving a JSON object that looks like this:

[{"Position":1,"Top":182,"Left":20,"Height":73,"Width":90},{"Position":2,"Top":69,"Left":103,"Height":98,"Width":1}]

How can I iterate through this data, lets say if i wanted to alert each separate value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

牵你的手,一向走下去 2024-11-17 17:25:03

普通的旧 JavaScript:

for(var i = 0; i < data.length; i++){
    for(var key in data[i]){
        alert(key + " : " + data[i][key]);
    }
}

和 jQuery:

$.each(data, function(index, element){
    $.each(element, function(key, value){
        alert(key + " : " + value);
    });
});

您需要在嵌套循环中进行迭代,因为您需要遍历数组中的所有元素,并且对于每个数组元素,遍历所有属性。

Plain old JavaScript:

for(var i = 0; i < data.length; i++){
    for(var key in data[i]){
        alert(key + " : " + data[i][key]);
    }
}

And jQuery:

$.each(data, function(index, element){
    $.each(element, function(key, value){
        alert(key + " : " + value);
    });
});

You need to iterate in a nested loop since you need to go over all elements in the array and for each array element, go over all properties.

南烟 2024-11-17 17:25:03

前面的例子可以工作,但它们很幼稚。不擅长编码的示例只会循环遍历数组,这不是很健壮。

假设您在代码隐藏方法中返回键/值对,并且您希望能够根据需要分离这些数据来使用。你就从这个开始吧。

[WebMethod]
    public static Dictionary<string, string> EditPromo(int promoId)
    {
        using (var db = new DataContext())
        {
            var q = db.Promos.Where(x => x.promoID == promoId).Select(x => x).Single();

            return new Dictionary<string, string>()
                       {
                           {"code", q.code},
                           {"label", q.label},
                           {"expiredate", string.Format("{0:M/d/yyyy}", q.expireDate)}
                       };
        }
    }

现在我们可以通过 jQuery Ajax 访问它,如下所示:

$.ajax({
        url: "/Manager/mPromo/Promo.aspx/EditPromo",
        context: $("#editPromo"),
        data: "{promoId:'" + promoid + "'}",
        success: function (msg)
        {
            var resp = msg.d;
            $("h1:first", this).text("Edit " + resp.code);
            $("input#txtDate", this).val(resp.expiredate);
        }
    });

注意我如何创建一个名为 resp 的变量来保存 msg.d。然后我可以使用 resp.ReturnedDictionaryKey。上面我使用了使用过的代码和过期时间。我可以随意使用它们。

The previous examples will work, but they are naive. No good at coding's example will just loop through an array, which isn't very robust.

Let's pretend that you return key/value pairs in your code behind method and you want to be able to pick apart this data to use however you want. You start with this.

[WebMethod]
    public static Dictionary<string, string> EditPromo(int promoId)
    {
        using (var db = new DataContext())
        {
            var q = db.Promos.Where(x => x.promoID == promoId).Select(x => x).Single();

            return new Dictionary<string, string>()
                       {
                           {"code", q.code},
                           {"label", q.label},
                           {"expiredate", string.Format("{0:M/d/yyyy}", q.expireDate)}
                       };
        }
    }

Now we can access it via jQuery Ajax like so:

$.ajax({
        url: "/Manager/mPromo/Promo.aspx/EditPromo",
        context: $("#editPromo"),
        data: "{promoId:'" + promoid + "'}",
        success: function (msg)
        {
            var resp = msg.d;
            $("h1:first", this).text("Edit " + resp.code);
            $("input#txtDate", this).val(resp.expiredate);
        }
    });

Notice how I created a variable to hold msg.d, called resp. I can then use resp.ReturnedDictionaryKey. Above I used used code and expiredate. I can use them however I please.

时间海 2024-11-17 17:25:03

试试这个。

$("#mybutton").click(function(){
    $.ajax({
        url: '/Member/GetPinPoints/@Model.Id',
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            //asp.net 3.5 plus wraps the return into a .d property
            var msg = data.hasOwnProperty("d") ? data.d : data;
            for(var i=0; i < msg.length; i++){
              alert(msg[i].Position);  
            }
        },
        error: function() {

        alert("error");
        }
    });
    return false;
});

Try this.

$("#mybutton").click(function(){
    $.ajax({
        url: '/Member/GetPinPoints/@Model.Id',
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            //asp.net 3.5 plus wraps the return into a .d property
            var msg = data.hasOwnProperty("d") ? data.d : data;
            for(var i=0; i < msg.length; i++){
              alert(msg[i].Position);  
            }
        },
        error: function() {

        alert("error");
        }
    });
    return false;
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文