【问题标题】:JQuery AJAX Done is not executingJQuery AJAX Done 没有执行
【发布时间】:2013-02-10 08:32:55
【问题描述】:
$('#loginForm').submit(function(e){

        var $inputs = $(this).find("input");
        var serializedData = $(this).serialize();   
        $inputs.prop("disabled", true);

        var request = $.ajax({
            url: "myurl",
            dataType: "json",
            type: "GET",
            data: serializedData,
        });

        request.done(function (response, textStatus, jqXHR){
            $('#loginMessage').text('GOOD');
        });

        request.fail(function (jqXHR, textStatus, errorThrown){
            $('#loginMessage').text('Some error occured. Please try again');
            console.error("The following error occured: ",errorThrown,jqXHR);
        });

        request.always(function () {
            $inputs.prop("disabled", false);
        });
        // prevent default posting of form
        e.preventDefault();         
    });

我是 jquery 的新手,在上面的代码中,.done 块没有执行,firebug 控制台显示此消息:-

GET myurl?userID=aman&password=aman 200 OK 37ms jquery....min.js(第 2 行)

出现以下错误:(空字符串)Object { readyState=0, status=0, statusText="error"}

服务器端脚本

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("userID");
        String password = request.getParameter("password");
        System.out.println("GET");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        Gson gson = new Gson();
        if(username.equals("aman") && password.equals("aman")){
            out.println(gson.toJson(new Boolean("true")));
        }else{
            out.println(gson.toJson(new Boolean("false"))); 
        }
        out.close();
    }

【问题讨论】:

  • 检查错误...为什么会得到它?
  • 代替 request.done 和 fail 尝试使用成功和错误,查看 jquery ajax api 的成功和错误
  • 我在问题中包含了firebug控制台日志,无法识别错误,如果有任何其他方法可以识别错误,请提及。谢谢
  • @Abu 我也试了成功,没有执行

标签: java jquery ajax json


【解决方案1】:

问题可能是您没有发送完整的 JSON。我从

输出结果
out.println(gson.toJson(new Boolean("true")));

你得到的只是这个词。尝试将其更改为类似的内容。

HashMap<String, Boolean> hm = new HashMap<String, Boolean>();
hm.put("success", true);
out.write(gson.toJson(hm));

运行我得到 {"success":true} 这是有效的 JSON。

【讨论】:

    【解决方案2】:

    不调用可能完成,因为调用的是失败。 由于 http 请求本身似乎有效,另一个可能的问题是它没有返回正确的 json 内容,而回复被解释为这样(因为 dataType: "json")。

    因此,您应该调查一下服务器返回的内容。

    【讨论】:

      【解决方案3】:

      我不知道为什么,但有时 firebug 断点给人的印象是 request.done() 中的代码没有执行。也许它只是被引导到控制台。

      尝试在 firebug 中测试没有断点的代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多