简体   繁体   中英

how to call spring controller in jquery ajax success method

I have created a spring controller and a jsp page. In jsp page I am using jquery ajax call to hit the controller. Now, this controller returns a json response as string. Now on based of json response in success method, I want to call a next controller call which will return a ModelAndView jsp page. How can I do this. Below is my code:

JSP Jquery ajax call:

$(document).ready(function(){
    $("#submitButton").click(function(e){
         var formData = getFormData();
         if(formData!=false){
         $.ajax({
            type: 'POST', 
            'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
            data: {jsonData: JSON.stringify(formData)},
            dataType: 'json',
            success: function(response){ 
                 try{
                    var strResponse=jQuery.parseJSON(response);
                }catch(err){}
                if(response.status=='ok')
                {
                    alert ("okokokokokokokokok");
                //I am successfully reaching till here. 
                //But in case of this alert box I want to call a 
                //controller which will return ModelAndView and 
                //should open a corresponding ModelAndView jsp page.
                //something like:
                /*
                $.ajax({
                type: 'GET', 
                'url': 'http://localhost:8080/Test_ReportingUI/abcxyz.htm',  
                )};
                */
                }
                else
                {
                    alert("ERROR!!");
                } 

            },
            timeout: 10000,
            error: function(xhr, status, err){ 
                if(response.status=='timeout')
                {   
                    alert('Request time has been out','');
                }
                console.log(status,err); 
            }
        }); }
     });
});

Controller class methods:

@RequestMapping (value="fieldMappingNext.htm", method=RequestMethod.POST)
@ResponseBody String addFieldMappingNext(@RequestParam String jsonData)
{
    String customerID =null;
    String objectID = null;
    String syncFieldName = null;
    String optMapping = null;
    JSONObject jsonResponse = new JSONObject();
    try{
        JSONObject requestedJSONObject = new JSONObject(jsonData);
        customerID = requestedJSONObject.getString("customerID");
        objectID = requestedJSONObject.getString("objectID");
        syncFieldName = requestedJSONObject.getString("syncFieldName");
        optMapping = requestedJSONObject.getString("optMapping");
    }catch(Exception exex){
        exex.printStackTrace();
    }
    if(optMapping.equalsIgnoreCase("direct")){
        long metadataID=rwCustomerService.getMetaDataID(customerID,objectID);
        List<RWFieldDetail> list=rwCustomerService.getFieldDetailNames(metadataID);
        request.setAttribute("customerID", customerID);
        request.setAttribute("objectID", objectID);
        request.setAttribute("optMapping", optMapping);
        request.setAttribute("syncFieldName", syncFieldName);
        request.setAttribute("fieldNames", list);
        try {
            jsonResponse.put("status", "ok");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return jsonResponse.toString();
}

Second Controller method that I want to call from jquery success method:

@RequestMapping (value="abcxyz.htm", method=RequestMethod.GET)
ModelAndView fieldMapping(){
ModelAndView modelAndView=new ModelAndView("FieldMappingMainScreenNext");
return modelAndView;
}

How do I do this.

Since the second handler method returns ModelAndView , you should redirect from the success callback:

...

success: function(response) {
    window.location.replace(response.url);
}

...

In your Java code you can use something like:

Map<String, String> map = new HashMap<String, String>();
if(condition1){
   map.put("url","url1.html");
}
if(condition2){
   map.put("url","url2.html");
}

Convert it to a JSON string and revert it back. Afterwards, in the jquery portion you'll get the response:

success:function(jsonStr){
    var obj = JSON.parse(jsonStr);
    var url = obj.url;
}

That is how you can get the url. If you want to load an other page or create an ajax call then you can do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM