jquery ajax 调用成功,如何更改包装器 javascript 函数中的全局变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11917734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:39:07  来源:igfitidea点击:

jquery ajax call success, how do i change a global variable in the wrapper javascript function?

javascriptjquery

提问by sammiwei

function ajax_test(str1){ 
  var url = "None" 
  jq.ajax({
    type:'post', 
    cache: false, 
    url: 'http://....' + str1, 
    success: function(data, status, xhr){ 
      url=data; 
    }, 
    error: function (xhr, status, e) {  
    }, 
    async: true, 
    dataType: 'json' 
  }); 
  return url 
} 

How can I set the global variable urlto be the returned success ajax data?

如何将全局变量url设置为返回的成功ajax数据?

采纳答案by Peter Olson

In Javascript, it is impossible for a function to returnan asynchronous result. The function will usually return before the AJAX request is even made.

在 Javascript 中,一个函数不可能return得到异步结果。该函数通常会在 AJAX 请求发出之前返回。

You can always force your request to be syncronous with async: false, but that's usually not a good idea because it will cause the browser to lock up while it waits for the results.

您总是可以强制您的请求与 同步async: false,但这通常不是一个好主意,因为它会导致浏览器在等待结果时锁定。

The standard way to get around this is by using a callback function.

解决这个问题的标准方法是使用回调函数。

function ajax_test(str1, callback){  
   jq.ajax({ 
     //... your options
     success: function(data, status, xhr){  
       callback(data);
     }
   });  
}  

and then you can call it like this:

然后你可以这样称呼它:

ajax_test("str", function(url) {
  //do something with url
});

回答by Terry Tang

Here is my example code for retrieving data from php, and then pass the value to a javascript global variable within ajax success function. It works for me!

这是我从 php 检索数据的示例代码,然后将值传递给 ajax 成功函数中的 javascript 全局变量。这个对我有用!

var retVal = null; 

function ajaxCallBack(retString){
    retVal = retString;
}

function readString(filename){
    $.ajax({  
        type: "POST",  
        url: "readString.php",  
        data: { 'fn': filename },      
        success: function(response){
            ajaxCallBack(response);
        }
    }); 
}

PHP code (readString.php):

PHP 代码(readString.php):

<?php

     $fn  = $_POST['fn'];

     $file = fopen("path/".$fn.".record","r");
     $string = fread($file,filesize("path/".$fn.".record"));
     fclose($file); 

     echo $string;  
?>

However, as $.ajax() sent requests asynchronously, which means it may return before the success callback runs, you should not rely on it runs sequentially and return the value by itself. Therefore, here we assign php response value to global value in callback function.

但是,由于 $.ajax() 异步发送请求,这意味着它可能会在成功回调运行之前返回,您不应该依赖它顺序运行并自行返回值。因此,这里我们将 php 响应值分配给回调函数中的全局值。