[英]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.