2016-03-21 89 views
0

我有像這樣的ajax json POST方法。Ajax json POST和Spring MVC控制器8

$(function() { 
       $('#formId').submit(function (event) { 
        event.preventDefault(); // prevent this form from being submited 
        var userJson = $('#id').val(); 
        alert(userJson); 
        $.ajax({ 
         type: "POST", 
         url: "/MobitelProgressTool/ajaxcall", 
         data: userJson, 
         contentType: "application/json; charset=utf-8", 
         dataType: "json", 
         success: function (data, textStatus, jqXHR) { 
          alert(data);//handle it in a proper way 
         }, 
         failure: function (jqXHR, textStatus, errorThrown) { 
          alert(textStatus);//handle it in a proper way 
         } 
        }); 
        alert("mm"); 
        return false; 
       }); 
      }); 

控制器來處理POST請求

@RequestMapping(value = {"/ajaxcall"}, method = RequestMethod.POST) 
    @ResponseBody// <== this annotation will bind Arr class and convert to json response. 
    public List<String> addAnotherAppointmenttt(HttpServletRequest request, HttpServletResponse response, @RequestBody String userJson, Model model, BindingResult errors) { 
     System.out.println("*******88888" + userJson); 
     //List<String> ll = stageViiChartDataServices.findByUpdated_Scope(userJson); 
     List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You"); 
     return messages; 
    } 

,但我不能讓mesages列表值,。我不確定如何更正上面的代碼。

回答

0

讀你的javascript我看到你發佈一個值在這種形式var userJson = $('#id').val();

通過這種方式,您可以在jQuery中詢問是否需要檢索一個值。但是你應該發佈一個json,而不是一個值。像這樣的認爲可能是罰款:

var value = $('#id').val(); 
var json = {'id': value} 

那麼我個人的意見是,如果有可能HttpServletRequest request, HttpServletResponse response在您的控制器不使用,而是使用Spring抽象,@RequestBody String userJson, Model model, BindingResult errors是好的!我希望這可以幫助你