user3819816
user3819816

Reputation: 11

how to retrieve the returned value from the controller in the jsp using the ajax

this is my javascript code

 <script type="text/javascript">
        function callMe() {
            var districtId = $("#district").val();
            alert(districtId);
            $.ajax({
                type: "POST",
                url: "addBranch",
                data: "districtId=" + districtId,
                success: function(response) {



                }
            });
        }

    </script> 

this is my controller code

@RequestMapping(value = "/addBranch", method = RequestMethod.POST)
public @ResponseBody 
List getForm1(@ModelAttribute Branch branch, Model model,@RequestParam("districtId")    
int districtId) {
    try {

       districtVillageList = villageService.getDistrictVillageList(districtId);

    } catch (Exception er) {
        log.error("error in addLoanType=" + er);
    }
    return districtVillageList;
 }

I am getting the list in the controller, but as i am new to ajax,i dont know how to retrieve the list in the ajax and use the retrieved values in jsp...Please can any one helo me??

Upvotes: 0

Views: 971

Answers (1)

Santhosh
Santhosh

Reputation: 8187

As you have returned the list in the controller, just get in the response and iterate it using for-in loop something like below,

<script type="text/javascript">
        function callMe() {
            var districtId = $("#district").val();
            alert(districtId);
            $.ajax({
                type: "POST",
                url: "addBranch",
                data: "districtId=" + districtId,
                success: function(response) {
                       for (var i in response){
                       // response[i].getterMethodHere
                      }   
                    }
            });
        }    
    </script> 

try using json objects to send the response instead of list. Learn More from jquery loop on Json data using $.each and jQuery loop over JSON result from AJAX Success?

Upvotes: 1

Related Questions