[英]how to use data from ajax success in another function?
我想在函数内部调用jquery ajax函数,如下所示:
function mine(time){
$.get("test.php", function(data){
var mytime=data;
});
alert(mytime);
}
它只是打印未定义。
我的test.php文件是这样的:
<?php echo time(); ?>
我希望'mydata'的值是php服务器的当前时间。
回调函数将在以后执行。 代替document.write
,使用jQuery的方法:
$.get("test.php", function(data){
var mytime=data;
// Replace 'body' with a selector for the element that displays time
$('body').text(mytime);
// Alternatively, call another function
someOtherFunction(mytime);
});
可能会有变量范围,所以像这样定义变量
var mytime;
function mine(time){
$.get("test.php", function(data){
mytime=data;
});
document.write(mytime);
}
您需要使用同步模式
function validerServeur(value) {
var retval;
$.ajax(
url: "test.php",
data: { valeur: value },
async: false, // <-- This disable asynchrone mdoe
succes: function(data) {
retval = data;
}
) ;
return retval;
}
在$ .get的处理程序中添加document.write(time),例如:
$.get("test.php", function(data){
var mytime=data;
document.write(mytime);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.