没有警报框,AJAX无法正常工作

编程入门 行业动态 更新时间:2024-10-26 19:24:25
本文介绍了没有警报框,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.

这里有几个选项:

  • 声明一个全局变量并执行同步调用,您可以使用发布的代码ABC执行此操作,也可以在POST调用之前调用 $ .ajaxSetup({async:false})。将返回值分配给全局变量并对其进行验证。
  • 使用jQuery的ajaxStop: $(document).ajaxStop(function(){//检查你的值在这里,仍然需要声明一个全局});
  • 将值写入隐藏的div /作为DOM中任何位置的属性,并定期定时检查它直到有值。
  • 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.
  • use jQuery's ajaxStop: $(document).ajaxStop(function() { //check your values here, still need to declare a global });
  • 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无法正常工作

    本文发布于:2023-11-27 05:28:45,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1636787.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:警报   无法正常   工作   AJAX

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!