2017-03-04 57 views
0

我从我的控制器返回一个列表。我如何从AJAX访问这些列表值?当我发出警报时,我不确定。如何访问从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 
       } 
      }); 
     } 
    }); 
}); 
+0

我看到你在表单上访问值与VAR inputIndex = $(“#指数”)VAL()。 。将该表单添加到问题中。 –

回答

0

你的问题是在你的JavaScript。对于第二个Ajax请求,您使用完整的属性而不是成功。在完整属性中指定的函数应该具有以下签名:函数(jqXHR jqXHR,String textStatus)所以,而不是您的json列表您收到jquery XHR object这就是为什么data [0]未定义。如果你希望你的列表,那么你应该得到这样的:

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