csdn产品小助手 2016-11-07 14:54 采纳率: 0%
浏览 9

异步:错误不起作用

I am using async:false. Therefore in case of success function, it should wait till it gets a response from the function and should stop executing the code that follows the success function.

However it executes the code following it. Shouldn't async lock the process? Now in mycase, I am making $('#val1loading').text('loading') which has to keep showing loading until it gets a success from the ajax call. But it doesn't.

$("#val").change(function() {
$('#val1loading').text('loading');

if ($('#val').val() != '') {
    $.ajax({
        url: "Functions.php",
        dataType: 'json',
        data: {
            async: false,
            'link': $('#val').val()
        },
        success: function(result) {
            $("#val1").val(result[0]);

        },
        error: function(xhr, status, error) {
            $("#val1").val('');

        }
    });
} else {
    //some code
}
$('#val1loading').text('');

});

  • 写回答

3条回答 默认 最新

  • weixin_33730836 2016-11-07 14:57
    关注

    The async: false should be in the main object passed to $.ajax, not contained within the data sub-object.

    That said, using synchronous AJAX is almost always a bad idea precisely because it does "lock the process" as you mentioned in the question.

    Get used to writing properly async code, where every action in the program happens via callbacks as a result of events (e.g. AJAX completion) or better yet use "Promises", e.g.:

    $('#val').on('change', function() {
        var $val1 = $('#val1');
        var $loading = $('#val1loading');
        var val = this.value.trim();
    
        if (val.length > 0) {
            $loading.text('loading');
            $.ajax({
                url: "Functions.php",
                dataType: 'json',
                data: { link: val },
            }).then(function(result) {
                $val1.val(result[0]);
            }).fail(function(xhr, status, error) {
                $val1.val('');
            }).always(function() {
                $loading.text('');
            });
        }
    });
    
    评论

报告相同问题?