【问题标题】:Ajax success not setting value of variableAjax成功没有设置变量的值
【发布时间】:2019-05-21 14:01:18
【问题描述】:

我对我的一个观点有一个简单的 ajax 调用。

var countAnchors;

$.ajax({
    url: countUrl,
    method: "GET",
    data: @Model.InitialTrainingId,
    success: function (result) {
        console.log("result: ",result);
        countAnchors = result;
    },
    error: function (jqXHR) {
        console.log(jqXHR);
        alert("There was a problem");
    }
});

console.log("countAnchors: ",countAnchors);

当我运行它时,在我看到的控制台中:

为什么countAnchors没有在success函数中赋值?

【问题讨论】:

标签: jquery ajax asp.net-mvc razor


【解决方案1】:

您可以创建一个function,因此每当收到回复时,您都可以为您的variable 赋值,如下所示:

var countAnchors=null;

  function result(r){
    countAnchors= r;//assigning value return
   console.log("countAnchors: ",countAnchors);
  }

    $.ajax({  
        type: "POST",  
        url: "readString.php",  
        data: { 'fn': filename },      
        success: function(response){
            result(response); //calling function
        },
       error: function (jqXHR) {
       console.log(jqXHR);
       alert("There was a problem");
      }
    }); 

【讨论】:

    【解决方案2】:

    你的日志条目给了你一个提示。

    除非您另外指定,否则 ajax 调用将异步运行。

    在这种情况下,您会在日志中看到您对 countAnchors 值的记录发生在 ajax 调用完成之前。仅仅因为它是在脚本块中较早编写的,并不意味着(在这种情况下)它在脚本块的下一部分执行之前就完成了。

    我敢打赌,这会给你一个值,并将这两行以预期的顺序返回到控制台日志:

    var countAnchors;
    
    $.ajax({
        url: countUrl,
        method: "GET",
        data: @Model.InitialTrainingId,
        success: function (result) {
            console.log("result: ",result);
            countAnchors = result;
            console.log("countAnchors: ",countAnchors);
            doSomething();
        },
        error: function (jqXHR) {
            console.log(jqXHR);
            alert("There was a problem");
        }
    });
    
    function doSomething()
    {
        alert('countAnchors: ' + countAnchors);
    }
    

    编辑:如果您需要一些与 countAnchors 的值有关的事情,请创建一个新的 javascript 函数并在设置 countAnchors 后从成功函数中调用它。

    【讨论】:

      【解决方案3】:

      因为

      console.log("countAnchors: ",countAnchors);
      

      在成功函数之前运行,此时'countAnchors'仍未定义

      【讨论】:

      • 那么,我如何知道countAnchors 是否被分配了正确的值?我该如何测试?
      • uhmm ..你可以在console.log("result: ",result) 之后马上查看
      • 但问题是我正在根据我在问题中发布的 ajax 调用之外的 countAnchors 的值执行条件语句。所以,如果它没有正确的值并且只有undefined,那么我的条件语句将无法按预期工作
      • 你必须在'success'里面做
      猜你喜欢
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-17
      • 1970-01-01
      相关资源
      最近更新 更多