如何从ajax访问控制器返回的列表值?

时间:2017-03-04 22:06:09

标签: jquery ajax spring jsp post

我从控制器返回一个列表。如何从AJAX访问这些列表值?当我发出警报时,我得到了不确定。

控制器

@ResponseBody
@RequestMapping(value="/practice/{category}/option", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
public List<Map<String, Object>> practicePageOption(@PathVariable("category") String category, @RequestParam("index") int index, ModelMap model, HttpSession session){

    //System.out.println(optionsList.get(index));
    //Result;
    //[{word=abdomen, meaning=karın}, {word=search, meaning=aramak}, {word=fund, meaning=kurmak}, {word=surgeon, meaning=cerrah}, {word=various, meaning=çeşitli}]
    return optionsList.get(index);
}

AJAX:

$('#pass').click(function(event) {
    var inputIndex = $('#index').val();
    $.ajax({
        type: "POST",
        url: "${pageContext.request.contextPath}/practice/${category}",
        async:false,
        data: { index: inputIndex },
        success: function(data){
            $('#label').text(data);
            $.ajax({
                type: "POST",
                url: "${pageContext.request.contextPath}/practice/${category}/option",
                async:false,
                contentType:"application/json; charset=utf-8",
                dataType:"json",
                data: { index: inputIndex },
                complete: function (data) {
                    //how can use data value
                    $('#optionA').text(data[0]);
                    alert(data[0]);  //undefined
                }
            });
        }
    });
});

1 个答案:

答案 0 :(得分:0)

您的问题出在您的javascript中。对于第二个ajax请求,您使用完整属性而不是成功。在complete属性中指定的函数应具有以下签名:Function(jqXHR jqXHR,String textStatus),因此您将收到jquery XHR object而不是您的json列表,这就是为什么data [0]未定义的原因。如果你想要你的清单那么你应该这样:

var myList = JSON.parse(jqXHR.responseText);
alert(myList[0]);