Javascript jQuery.ajax 成功回调函数未执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2787180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:54:38  来源:igfitidea点击:

jQuery.ajax success callback function not executed

javascriptjqueryajaxcallback

提问by Frank Michael Kraft

I have a JavaScript Ajax call (jQuery.ajax), that does not execute the success callback function.

我有一个 JavaScript Ajax 调用 (jQuery.ajax),它不执行成功回调函数。

$.ajax({
        url: target,
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        // type: 'GET',
        dataType: 'jsonp',
        error: function (xhr, status) {
            alert(status);
        },
        success: function (result) {
            alert("Callback done!");
            // grid.dataBind(result.results);
            // grid.dataBind(result);
        }
    });

I see in firebug, that the request is posted and the correct result in terms of the json is returned as expected. What is wrong?

我在萤火虫中看到,请求已发布,并按预期返回了 json 方面的正确结果。怎么了?

回答by Cagdas

For many times I have encountered similar problems and most of the time the reason was a malformed json. Try getting the result as text data type to see whether this is your problem.

很多时候我都遇到过类似的问题,大多数时候是因为json格式错误。尝试将结果作为文本数据类型,看看这是否是您的问题。

Also, I'd like to ask if you're using a parameter like "&jsoncallback=?" in your url, since your data type is jsonp instead of simple json.

另外,我想问一下您是否使用了像“&jsoncallback=?”这样的参数。在您的 url 中,因为您的数据类型是 jsonp 而不是简单的 json。

回答by systempuntoout

Your $.ajaxcall with dataType: 'jsonp'could work in these scenarios:

您的$.ajax通话dataType: 'jsonp'可以在这些情况下工作:

  1. You are calling a url on the same domain of your page.
  2. You are calling a url out of your domain of your page that supports callback
  1. 您正在页面的同一域上调用 url。
  2. 您正在从支持回调的页面域中调用 url

If you are out of these two cases, you can't do anything since you can't make cross site XmlHttpRequest calls.

如果您不在这两种情况下,则无法进行任何操作,因为您无法进行跨站点 XmlHttpRequest 调用。

回答by MikeBaz - MSFT

This is an old question, but I suspect people still hit this.

这是一个老问题,但我怀疑人们仍然会遇到这个问题。

I fought this for some time, and eventually gave up and moved to the deferred model. (I've been using jQuery long enough that I was in the "old" way habits still...) As soon as I moved to a deferred model, things started to work. I have no idea why the old way didn't work, but no longer care. (This question pre-dates the new model.)

我为此抗争了一段时间,最终放弃并转向延迟模型。(我使用 jQuery 的时间已经足够长了,以至于我仍然处于“旧”的习惯中......)一旦我转向延迟模型,事情就开始起作用了。我不知道为什么旧的方法不起作用,但不再关心。(这个问题早于新模型。)

cf. https://stackoverflow.com/a/14754681/199172

参见 https://stackoverflow.com/a/14754681/199172

回答by Thanh Nguyen

You need to have set async property to false.

您需要将 async 属性设置为 false。

$.ajax({
        url: target,
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        // type: 'GET',
        dataType: 'jsonp',
        async = false,
        error: function (xhr, status) {
            alert(status);
        },
        success: function (result) {
            alert("Callback done!");
            // grid.dataBind(result.results);
            // grid.dataBind(result);
        }
    });

回答by Xorcist

This just happened to one of my co-workers, so I figure I'd add my solution as well.

这只是发生在我的一位同事身上,所以我想我也会添加我的解决方案。

We could see the ajax call being made, and could see the proper response coming back in Fiddler (status 200 / completely valid JSON), but it would never hit the error, success, or complete callbacks. Adding async: false to the ajax call would make it work, but that wasn't really a proper solution. Additionally placing an alert directly after the ajax call (without the async: false), and waiting a few seconds once the alert was shown, would somehow force the ajax callbacks to work . Very odd indeed...

我们可以看到正在执行的 ajax 调用,并且可以看到 Fiddler 中返回的正确响应(状态 200/完全有效的 JSON),但它永远不会遇到错误、成功或完整的回调。将 async: false 添加到 ajax 调用将使其工作,但这并不是一个真正的解决方案。此外,在 ajax 调用之后直接放置警报(没有 async:false),并在显示警报后等待几秒钟,会以某种方式强制 ajax 回调工作。确实很奇怪...

Turns out, the function with the ajax call was bound to an input of type="submit", which was the source of this odd behavior. Changing the input to type="button" corrected it.

事实证明,带有 ajax 调用的函数绑定到 type="submit" 的输​​入,这是这种奇怪行为的根源。将输入更改为 type="button" 更正了它。

回答by EuanAnil B

Jquery Ajax call to a servlet with mutliple parameters was not calling success or error even though the call was succesfull. It was bound to a submit button. Changing it returned a success event.

即使调用成功,对具有多个参数的 servlet 的 Jquery Ajax 调用也未调用成功或错误。它绑定到一个提交按钮。更改它返回一个成功事件。

Here is my reference code in case someone needs it for reference.

这是我的参考代码,以防有人需要参考。

$(document).ready( function () {    
    $("#buttonSave").click(function() {
        alert('incustsave');
        var name = $("#custname").val();
        var gstnumber = $("#gstnumber").val();
        var custbizname = $("#custbizname").val();
        var email = $("#email").val();
        var address = $("#address").val();
        var street = $("#street").val();
        var city = $("#city").val();
        var zip = $("#zip").val();
        var phone = $("#phone").val();
        var country = $("#ctry").val();

        var inputArray = [name, gstnumber, custbizname, email, address, street, city, zip, phone, country];
        var Success = false;
        alert('added_button_and_dt');
        $.ajax({  
            type: "POST",
            url: "RegisterCustomerServlet",               
            data: {'input': inputArray},
            dataType: 'json',

            success: function (data) {
                alert('sucess');
            },
            error: function (e) {
                alert('error');
            }
        });
    });
});

HTML with Bootstrap3 (Button reference)

带有 Bootstrap3 的 HTML(按钮参考)

<!-- Button -->
<div class='wrapper text-center'>
    <div class="btn-group">
        <button type="button"  id="buttonSave" class="btn btn-primary">Save</button>
    </div>
</div>

Servlet Reference

Servlet 参考

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    HashMap<String,String>  map = new HashMap<String,String>();
    CustomerDAO custinfo = new CustomerDAO();
    Gson gson = new Gson();
    CustomerVO vo = new CustomerVO();

    String[] myJsonData = request.getParameterValues("input[]");
    logger.info("in custregisterjsoninput" + myJsonData[0] + myJsonData[2] + myJsonData[3] + myJsonData[4]);

    map.put("custname", myJsonData[0]);
    map.put("getsnumber", myJsonData[1]);
    map.put("custbizname", myJsonData[2]);

    map.put("email", myJsonData[3]);
    map.put("address", myJsonData[4]);
    map.put("street", myJsonData[5]);
    map.put("city", myJsonData[6]);          
    map.put("pincode", myJsonData[7]);
    map.put("mainphone", myJsonData[8]);
    map.put("country", myJsonData[9]);

    try {
        vo = custinfo.saveCustomerInfo(map);
    } catch (Exception e) {
        logger.info("aftercall"+e.getMessage());
        throw new ServletException(e);
    }  
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(Utility.convertPOJOtoJason(vo));
}