简体   繁体   中英

Handling response to AJAX from servlet

This is my servlet class code where I am setting response.

        PrintWriter out = response.getWriter();
        response.setContentType("text/html");

        if(status.equals("Fail")) {
            out.println(status);  
        }else {
            out.println(status);  
        }

        out.flush();

This is my AJAX where I need to show a message depending upon SUCCESS/FAIL response from Servlet.

           $.ajax({
                    url: "ImportFile",
                    type: "POST",
                    data: new FormData(document.getElementById("fileForm")),
                    enctype: 'multipart/form-data',
                    processData: false,
                    contentType: false,
                    success :function(data) {
                           console.log('RESPONSE: ',data);
                           if(data == "Success"){
                               $(".impostSuccess").modal('show');
                           }else{
                               $(".impostFail").modal('show');
                           }
                           file.val('');
                       },
                       error :function(err){
                           file.val('');
                           console.log('RESPONSE: ',data);
                       }   
            });

Wherever my response is "Success", Else part is executing and that modal is shown.

How should I handle this?

you can show message like this

       $.ajax({
                url: "ImportFile",
                type: "POST",
                data: new FormData(document.getElementById("fileForm")),
                enctype: 'multipart/form-data',
                processData: false,
                contentType: false,
                success :function(res) {
                       console.log('RESPONSE: ',res);
                       $(".impostSuccess").modal('show');
                       file.val('');
                   },
                   error :function(err){
                       file.val('');
                       console.log('RESPONSE: ',err);
                       $(".impostFail").modal('show');

                   }   
        });

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