Hayi
Hayi

Reputation: 6236

Access to the variable I put in the model in my jquery script

i want to access in my jquery script to the variable cardlist i put in the model:

@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";

}

My jquery ajax call:

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");
    }
});

}

Upvotes: 0

Views: 263

Answers (2)

Mehran Hatami
Mehran Hatami

Reputation: 12961

use Gson api to create a json string and put it in your model. to use Gson add this to your pom.xml:

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

then do this in your java code:

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

then read it in your js file like this:

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);
}

Upvotes: 0

Evgeni Dimitrov
Evgeni Dimitrov

Reputation: 22506

Change you method as:

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


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

    return listlostcard ;

}

make sure you have Jackson Mapper in the classpath. Then you can access the list in the success mehtod.

To use the response in the you can use:

success : function(responce) {  

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

Upvotes: 1

Related Questions