访问我在jquery脚本中放入模型的变量

时间:2014-01-08 18:50:30

标签: javascript jquery ajax spring spring-mvc

我想在我的jquery脚本中访问我放入模型的变量cardlist

@RequestMapping(value="/searchlostcard") 
public  
String searchlostcard(@ModelAttribute(value="searchform") SearchForm searchForm
        ,HttpServletRequest request, Map<String, Object> model) {   


    List<Lostcard> listlostcard = lostcardRepository.findByNom(searchForm.getValue());

    model.put("cardlist", listlostcard);

    return "search/results";

}

我的jquery ajax电话:

function searchAjax() {
$.ajax({
    url : 'searchlostcard',
    type: 'POST',
    data:$('#formSearch').serialize(),
    success : function(responce) {  

        /* how can i acces to my List of object (listlostcard) ? */
        $('#page_grid').html(responce);
    },      
    error : function(){
        alert("error");
    }
});

}

2 个答案:

答案 0 :(得分:1)

将方法更改为:

@RequestMapping(value="/searchlostcard") 
@ResponseBody
public  
List<Lostcard> searchlostcard(@ModelAttribute(value="searchform") SearchForm searchForm
        ,HttpServletRequest request) {   


    List<Lostcard> listlostcard = lostcardRepository.findByNom(searchForm.getValue());

    return listlostcard ;

}

确保在类路径中有Jackson Mapper。 然后,您可以访问成功mehtod中的列表。

要使用响应,您可以使用:

success : function(responce) {  

    jQuery.each(response, function(i, val) {
                    alert(val.someProperty);
                });
}

答案 1 :(得分:0)

使用Gson api创建一个json字符串并将其放入模型中。使用Gson将此添加到您的pom.xml

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>1.7.1</version>
</dependency>

然后在你的java代码中执行此操作:

List<Lostcard> listlostcard = lostcardRepository.findByNom(searchForm.getValue());
Gson gson = new GsonBuilder().create();
String json = gson.toJson(listlostcard);
model.put("cardlist", json);
return "search/results";

然后在你的js文件中读取它:

success : function(responce) {  

    var cardlist = JSON.parse(responce);
    var tbl = document.createElement("table");
    for(var i=0;i<cardlist.length;i++){
        var row = tbl.insertRow(i);
        //let's say you have ID and title in your model
        var idCell = row.insertCell(0);
        idCell.innerHTML = cardlist[i]["ID"];
        var titlecell = row.insertCell(1);
        titlecell.innerHTML = cardlist[i]["title"];
    }
    $('#page_grid').append(tbl);
}