2016-08-31 139 views
-1

我試圖向我的控制器發送一個AJAX調用,其代碼如下所示。現在我面臨的問題是,即使我能夠檢索控制器中的數據並隨後處理它,它也不會通過AJAX調用返回到jsp頁面。使用Spring MVC控制器調用Ajax

@SuppressWarnings("unchecked") 
@RequestMapping(value="/movie", method=RequestMethod.GET) 
public @ResponseBody Person search(HttpServletRequest request, HttpServletResponse response) throws IOException{   
    String name = request.getParameter("uname1"); 
    System.out.println(name); 
    List<Person> movie = personDAO.search(name); 
    Person per = new Person(); 
    for (java.util.Iterator<Person> iterator = movie.iterator(); iterator.hasNext();){ 
     per = iterator.next(); 
    } 

    System.out.print(per + " Wtf"); 
    return per; 
} 

這是我的AJAX調用:

 $.ajax({ 
     url: 'movie.html', 
     dataType: "json", 
     type: "GET", 
     contentType: 'application/json', 
     mimeType: 'application/json', 
     data: 'uname1=' + $('#element0').val(), 
     success: function(data){ 
       $('#col1').text(data.name); 
       $('#col2').text(data.pname); 
       $('#col3').text(data.wname); 
       $('#col4').text(data.lname); 
     }, 
     error: function(xhr, status, error) { 
       $('#col1').text("Undefined"); 
       $('#col2').text("Undefined"); 
       $('#col3').text("Undefined"); 
       $('#col4').text("Undefined"); 
     } 
    }); 

附在下面是輸出的屏幕截圖: Eclipse Output

回答

1

而不是返回一個對象。您應該使用','分隔符返回一個字符串,並將其拆分爲在視圖中獲得所需的輸出。

根據mozilla documentation,ResponseText可以是string或xml。你正在傳遞一個可能成爲問題的對象。

這裏有一個link獲得逗號分隔字符串,並在視圖

1

所以使用它,問題是我的URL映射。在編輯我的問題之前,我的代碼有一些評論部分解析了Person對象並將其元素插入到JSON對象中。問題是,我利用我的AJAX調用的URL有.html擴展和Spring實際使用的URL擴展到決定返回什麼類型的內容,如中提到:

@ResponseBody not working with spring 4.2.4 - not a duplicate I have checked all others

所以通過修改我的web.xml中的URL模式,如下所示:

<servlet-mapping> 
    <servlet-name>dispatcher</servlet-name> 
    <url-pattern>*.html</url-pattern> 
    <url-pattern>*.json</url-pattern> 
</servlet-mapping> 

然後將我的AJAX調用中的url更改爲movie。 JSON

 $.ajax({ 
     url: 'movie.json', 
     dataType: "json", 
     type: "GET", 
     contentType: 'application/json', 
     mimeType: 'application/json', 
     data: 'uname1=' + $('#element0').val(), 
     success: function(data){ 
       $('#col1').text(data.name); 
       $('#col2').text(data.pname); 
       $('#col3').text(data.wname); 
       $('#col4').text(data.lname); 
     }, 
     error: function() { 
       $('#col1').text("Undefined"); 
       $('#col2').text("Undefined"); 
       $('#col3').text("Undefined"); 
       $('#col4').text("Undefined"); 
     } 
    }); 

我能夠達到預期的效果。