2017-08-08 98 views
1

我是一名初學者,所以我提出了很多問題。我希望你明白。如何從ajax中獲得Controller返回的模型的值?

AdminController.java

@RequestMapping(value="show_allMember.do",produces = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST) 
    public @ResponseBody String memberList(ModelAndView mav) 
    { 
     List<HashMap<String, Object>> members = aService.getMemberList(); 
     mav.addObject("mList",members); 

     System.out.println("model is that : " + mav); 

     return "" + mav ; 
    } 

adminMainPage.jsp

function show_allMember() 
{ 
    $('.member_management_area').css('display','block'); 
    $('.member_management').css('color','#fe4978'); 

    $.ajax 
    ({ 
     type: 'POST', 
     url: 'http://localhost:8080/rachelivf/show_allMember.do', 
     dataType:'JSON', 
     success: function(mList) 
     { 
      console.log(mList); 
      $.each(response.mList, function(index, value) 
      { 
       console.log(response.list); 
      }); 
     }, 
     error: function(xhr,ajaxOptions,thrownError) 
     { 
      if(xhr.status == 404) 
     { 
       alert(thrownError); 
     } 
     } 
    }); 
} 

我試圖找到路。但它失敗了。

我想從控制器返回的模型的值在 ajax中並將其顯示在jsp中。

但我不知道如何。

作爲初學者,我不太瞭解,所以我問了很多問題。 如果我提供了正確的信息,請讓我知道。 請讓我知道,如果問題的要點是錯誤的。 我需要你的意見。

回答

1

更改return typeList<HashMap<String, Object>>代替String並返回members

@RequestMapping(value="show_allMember.do",produces = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.GET) 
public @ResponseBody String memberList(ModelAndView mav) 
{ 
    List<HashMap<String, Object>> members = aService.getMemberList(); 
    return members ; 
    //OR 
    //return aService.getMemberList(); 

} 

在阿賈克斯成功嘗試訪問作爲

type: 'GET', 
success: function(mList) 
    { 
     console.log(mList); 
     $.each(response.mList, function(index, value) 
     { 
      console.log(value.yourMapKey); 
     }); 
    }, 

改變method = RequestMethod.POSTmethod = RequestMethod.GET 希望這有助於...

+0

出現錯誤406()錯誤TT –

+1

改變的價值' value =「/ show_allMember.do」'add'/' –

+1

你添加了'Jackson'圖書館罐子嗎? –

1
  1. 您不需要使用GET從服務器獲取數據。

  2. 您不需要使用ModelAndView。它使用ViewResolver創建html頁面 - 它採用字符串視圖名稱的形式並將其放入模型的表單對象中。

您可以直接從方法返回所需的數據:

@RequestMapping(value="show_allMember.do",produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.GET) 
    public @ResponseBody List<HashMap<String, Object>> memberList() 
    { 
     return aService.getMemberList(); 
    } 

和修復的要求:在開發商TOOS

$.ajax 
({ 
    type: 'GET', 
    url: 'http://localhost:8080/rachelivf/show_allMember.do', 
    dataType:'JSON', 
    success: function(response) 
    { 
     $.each(response, function(index, value) 
     { 
      console.log(value); 
     }); 
    }, 
    error: function(xhr,ajaxOptions,thrownError) 
    { 
     if(xhr.status == 404) 
    { 
      alert(thrownError); 
    } 
    } 
}); 
+1

Ajax代碼好嗎? –

+1

更新的答案 - 添加固定的ajax – Nikolay

+1

成功:在函數(響應)部分中,響應是否包含控制器返回的值? –