[英]How do I change the output of the success function based on a variable using jQuery/Ajax?
[英]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
}
如何將全局變量url
設置為返回的成功 ajax 數據?
在 Javascript 中,函數不可能return
異步結果。 該函數通常會在 AJAX 請求發出之前返回。
您總是可以強制您的請求與async: false
,但這通常不是一個好主意,因為它會導致瀏覽器在等待結果時鎖定。
解決這個問題的標准方法是使用回調函數。
function ajax_test(str1, callback){
jq.ajax({
//... your options
success: function(data, status, xhr){
callback(data);
}
});
}
然后你可以這樣稱呼它:
ajax_test("str", function(url) {
//do something with url
});
這是我從 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 代碼(readString.php):
<?php
$fn = $_POST['fn'];
$file = fopen("path/".$fn.".record","r");
$string = fread($file,filesize("path/".$fn.".record"));
fclose($file);
echo $string;
?>
但是,由於 $.ajax() 異步發送請求,這意味着它可能會在成功回調運行之前返回,您不應該依賴它順序運行並自行返回值。 因此,這里我們將 php 響應值分配給回調函數中的全局值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.