$.ajax()方法在请求成功后老是执行error中的函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33800083/article/details/80588243

  • JS中的ajax 请求如下:
$.ajax({
            url: default_setting.formObj.action,
            type: "POST",
            data: jsonObj,
            dataType: "json",
            success: function(res) {
                var callbacks = $.Callbacks('stopOnFalse');
                callbacks.add(default_setting.formObj.onSuccess)
                callbacks.fire(res);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // var res = eval("(" + XMLHttpRequest.responseText + ")");
                // alert(res.message);
                alert("Operation failed");

            }

        })

后台返回时返回了一个String类型的单数,就造成了老是执行error中的函数的现象,查看文档,发现Jquery ajax方法中的dataType的说明:预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断。由此可见我这里指定了json类型,返回了text类型,所以走了error的回调。

解决:将dataType去掉,就能正常执行回调,但是我不推荐。在真实项目中,应该制定一个ajax请求返回结果类(比如JsonBean),所有ajax请求方法的返回类型都应该是JsonBean,这样指定dataType=’json’,不会出现其他幺蛾子。

JsonBean的实体可以是这样的:

public class JsonBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private boolean success;
    private String code;
    private Object result;

    // 构造方法,getter方法 略

}

第二种可能:

当你使用ajax的事件源是button(button在form中,默认是自动提交的)或href时,使用Jquery的Ajax时就会出现这种问题,最后将Button加上了一个type="button"该问题就解决了,(如果是href就将值设置为#)










猜你喜欢

转载自blog.csdn.net/qq_33800083/article/details/80588243