简体   繁体   English

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

[英]jquery ajax call success, how do I change a global variable in the wrapper javascript function?

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 url to be the returned success ajax data?如何将全局变量url设置为返回的成功 ajax 数据?

In Javascript, it is impossible for a function to return an asynchronous result.在 Javascript 中,函数不可能return异步结果。 The function will usually return before the AJAX request is even made.该函数通常会在 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
});

Here is my example code for retrieving data from php, and then pass the value to a javascript global variable within ajax success function.这是我从 php 检索数据的示例代码,然后将值传递给 ajax 成功函数中的 javascript 全局变量。 It works for me!这个对我有用!

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.但是,由于 $.ajax() 异步发送请求,这意味着它可能会在成功回调运行之前返回,您不应该依赖它顺序运行并自行返回值。 Therefore, here we assign php response value to global value in callback function.因此,这里我们将 php 响应值分配给回调函数中的全局值。

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

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