2016-08-31 142 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"); 
     } 
    }); 

我能够达到预期的效果。