为什么ajax的返回值无法赋值?index.htm代码:<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function test(){
$.ajax({
url:"laji.php",
success:function(d){
return d;
}
});
}
function hello(){
var x=test();
alert(x);
}
</script>
<button onclick="hello();">hello</button>
<script type="text/javascript">
function test(){
$.ajax({
url:"laji.php",
success:function(d){
return d;
}
});
}
function hello(){
var x=test();
alert(x);
}
</script>
<button onclick="hello();">hello</button>
原因是AJAX是异步交互,不会等到return返回的。你对结果的处理放在jquery的success里即可
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function test(){
$.ajax({
url:"laji.php",
success:function(d){
alert(d);
return d;
//或者这里调用你后面的处理。
}
});
}
function hello(){
var x=test();
}
</script>
<button onclick="hello();">hello</button>