简体   繁体   中英

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?

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

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.

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. 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

     $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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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