jQuery Ajax-如何处理json响应 [英] jquery ajax - how to handle the json response

查看:98
本文介绍了jQuery Ajax-如何处理json响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对我的ajax调用的响应.我想处理每个数组元素以更新页面上具有Letter元素值的相应按钮的标题.我需要更换警报(响应);遍历json数组.

This is the response to my ajax call. I want to handle each array element to update the title of a corresponding button on my page that has the value of the Letter element. I need to replace the alert(response); with a loop over the json array.

{"COLUMNS":["PAGESNUM","LETTER"],"DATA":[["372","A"],["922","B"],["779","C ],[" 3‌78," D],[" 132," E],[" 353," F],[" 551," G],[" 591, "H"],["6","I"],["340","J"],["‌261","K"],["314","l"],["837 ," M],[" 88," N],[" 120," O],[" 303," P],[" 14," Q],[" ‌ 355'',"R"],["762","S"],["235","T"],["12","U"],["44","V"],[ "581","W"],["49","Y"],["‌19","Z"]]}}

{"COLUMNS":["PAGESNUM","LETTER"],"DATA":[["372","A"],["922","B"],["779","C"],["3‌​78","D"],["132","E"],["353","F"],["551","G"],["591","H"],["6","I"],["340","J"],["‌​261","K"],["314","l"],["837","M"],["88","N"],["120","O"],["303","P"],["14","Q"],["‌​355","R"],["762","S"],["235","T"],["12","U"],["44","V"],["581","W"],["49","Y"],["‌​19","Z"]]}

$.ajax({
    type: "Get",
    url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json",
    data: "nbw=" + nbw,
    datatype: "html",
    success: function (response) {
        //usercount = parseInt(response.substring(0, 10));
        ///$(_$this.target).attr('title', usercount);
        alert(response);
    },
    error: function (xhr, textStatus, errorThrown) {
        alert('errorThrown');
    }
});

推荐答案

javascript区分大小写,因此您要将该参数设置为dataType,如果要返回JSON,则不要告诉您期望使用"html"的jQuery

javascript is case sensitive, so you're going to want to make that parameter dataType and if you're getting JSON back, then don't tell jQuery that you're expecting "html"

 dataType: "json",
    success: function (response) {
        alert(response.DATA[0][1]);//should alert "A"
    }

如果需要执行一些循环,则您的数组为response.COLUMNSresponse.DATA(这是数组的数组).

If you need to do some looping, your arrays are response.COLUMNS and response.DATA (which is an array of arrays).

var numCols = response.COLUMNS.length;
for( var i = 0; i < numCols; i++ ){
    response.COLUMNS[i]
}

或循环遍历嵌套数组

var numData = response.DATA.length;
for( var i = 0; i < numData; i++ ){
    for( var j = 0; j < response.DATA[i].length; j++ ){
        response.DATA[i][j]
    }
}

这篇关于jQuery Ajax-如何处理json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆