没有警报框,AJAX无法正常工作 [英] AJAX not working without alert box

查看:109
本文介绍了没有警报框,AJAX无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此代码:

I'm trying to use this code:

$('#form1').on('submit', function(){
    var txtItemCode = $('#txtItemCode').val();
    $.post("userExist.php", {
        txtItemCode: txtItemCode,
    }, function(data,status){
        //alert("Data: " + data + "\nStatus: " + status);
        $('#status').html(data);    
        reply = data;
        //alert(reply);
    });
    alert('');
    if (reply=='OK'){
        return false;
    }
});

我需要检查 data ==OK并返回false,但当我删除 alert 时,它不再有效。为什么会这样,以及如何使其工作?

I need to check if data=="OK" and return false, but when I remove the alert, it no longer works. Why is this, and how can I make it work?

推荐答案

引入警报时它起作用的原因是因为它停止了执行并为异步调用提供足够的时间来完成。

The reason it works when you introduce the alert is because it stops execution and gives enough time for the asynchronous call to finish.

您没有获得正确的值,因为在发布请求完成并执行回调时javascript已经完成执行。

You're not getting the right value because by the time the post request is finished and the callback is executed your javascript has already finished executing.

这里有几个选项:


  1. 声明一个全局变量并执行同步调用,您可以使用发布的代码ABC执行此操作,也可以在POST调用之前调用 $ .ajaxSetup({async:false})。将返回值分配给全局变量并对其进行验证。

  2. 使用jQuery的ajaxStop: $(document).ajaxStop(function(){//检查你的值在这里,仍然需要声明一个全局});

  3. 将值写入隐藏的div /作为DOM中任何位置的属性,并定期定时检查它直到有值。

  1. Declare a global variable and perform a synchronous call, you can either do it with the code ABC posted or call $.ajaxSetup({ async: false }) before your POST call. Assign the return value to the global variable and validate against that.
  2. use jQuery's ajaxStop: $(document).ajaxStop(function() { //check your values here, still need to declare a global });
  3. Write the value to a hidden div/as an attribute anywhere in the DOM and have a timer that periodically checks it until there's a value.

这篇关于没有警报框,AJAX无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆