繁体   English   中英

在 ajax/jquery 调用中使用成功 function 之外的变量

[英]Use variable outside the success function from an ajax/jquery call

我有以下代码

var test;

 $.ajax({
    type: "GET",
    url: "../views/person/controller.php?actor=person&action=checkAge",
    data: "age=" + value,
    success: function(msg){
        console.log(msg);
        test = msg; 
    },
});

Validate.fail(test);

现在测试 var 应该像控制台所说的那样给出 true 或 false 。 但是 test var 给了我未定义的为什么?

 var test; // <-- (1) This code runs first  
 $.ajax({  // <-- (2) Then this runs  
    type: "GET",
    url: "../views/person/controller.php?actor=person&action=checkAge",
    data: "age=" + value,
    success: function(msg){
        console.log(msg); //<-- (4) Finally this is run. IF your request is a success 
        test = msg; 
    },
 });
 Validate.fail(test); // <-- (3) This runs third  

查看代码运行的顺序。 您的变量此时根本不可用,因为它在通过回调触发代码时运行

可能是因为 Validate.fail(test) 在异步调用之后立即发生。 请记住它是异步的,这意味着它与您页面上运行的 javascript 并行执行。

var test;
 $.ajax({
    type: "GET",
    async: false,
    url: "../views/person/controller.php?actor=person&action=checkAge",
    data: "age=" + value,
    success: function(msg){
        console.log(msg);
        test = msg; 
    },
});
Validate.fail(test);

//让你的ajax函数同步,设置json参数“async:false”,所以javascript必须等到test被赋值。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var xm;

  $("#txt").ajaxComplete(function(){
    $('#txt').html(xm);
  });

  $("button").click(function(){

    $.ajax({
      url: 'DBresult_load.php',
      dataType: 'html',
      data: { },                 //you can pass values here
      success: function(result) {xm =result;}
    });
  });


});
</script>
</head>
<body>

<div id="txt"><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
</body>
</html>

这是从 Ajax 请求将值传递给变量的解决方案。 希望这可以帮助。

$.when(your_Ajax_Function()).done(function(){
            //this code is executed when all ajax calls are done
            //put your function here
            Validate.fail(test);


        });

当您在声明“test”之前删除“var”会发生什么?

我不确定如何使用 jQuery 处理回调函数,因为它包含在其他一些扩展方法中。但是我说在test变量的声明中将 var 排除在外的原因是var将 test 分配为相对的到范围。 如果您的回调以某种方式处理,您可能会失去定义test的范围。 您可能希望删除var分配并将其保留为全局变量。 也许这会让它可见?

编辑:: 没有意识到你在异步请求之后的函数调用中引用了这个术语——我建议在你的回调中包含最后一个语句。

:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM