0

Why springmvc return some kind of String will cause ajax error!

when controller return Integer like 123 ,It works fine;

when controller return Integer string like "123",It works fine;

when controller return String like "abc", the ajax will error!

The problem just like https://www.mkyong.com/jquery/jquery-ajax-request-return-200-ok-but-error-event-is-fired/

It is just simple ajax request to springmvc controller

ajax request

           $.ajax({
                type: "POST",
                url: "/test",
                data: JSON.stringify(json),
                dataType: "json",
                async : false,
                contentType: "application/json",
                success: function(msg){
                    alert(msg);
                    debugger;
                    result = msg;
                },
                error: function(msg){
                    debugger;
                    alert(msg);
                }
            })

controller file:

         @RequestMapping("test")
         public String test(){
          //return "123"; ajax works fine
           return 123; ajax works fine
           return "abc";  //ajax parsererror
         }

I expect all kind of String will be fine including String like "abc" !
Can anyone help me !
Thanks!

jack
  • 3
  • 1

1 Answers1

0

Because Json ,123 is a qualified JSON , because it is considered as number . But abc is not qualified JSON , "abc" is a qualified JSON . SpringMvc returns to front web with abc ,not "abc", so ajax can not resolve it .

Two solutation i can consider. First answer is : use an Util class to decorate abc with "abc"; Every time you return String , you need do so troubly.

public class StringUtils {
    public static String modifyReturnJson(String str){
        return  "\""+str+"\"";
    }
}
@RequestMapping("/test")
    public String test() throws IOException {
        return StringUtils.modifyReturnJson("123");
        //return "123"; ajax works fine
//        return 123; //ajax works fine
//        return "abc";  //ajax parsererror
    }

Second way:remove dataType: "json"

  • Thank you for your response! I get it, And I also found the same answer on https://stackoverflow.com/questions/6186770/ajax-request-returns-200-ok-but-an-error-event-is-fired-instead-of-success?rq=1 – jack Apr 18 '19 at 06:40