jquery ajax获取返回值

osm*_*ler 3 javascript ajax jquery

我想获得html页面的"打印价值".

我试过下面的查询,但showGetResult()只返回'null value'

但我的apache服务器日志打印我尝试此代码时访问index.php.

(index.php只是打印helloworld)

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"><\script>
<script type="text/javascript">
function showGetResult( name )
{
     var result = null;
     jQuery.ajax({
        url: 'http://localhost/index.php',
        type: 'get',
        dataType: 'text/html',
        success:function(data)
        {
            alert(data);
            result = data;
        } 
     });
     return result;
}

document.write(showGetResult('test'));
</script>
Run Code Online (Sandbox Code Playgroud)

Jam*_*ice 5

这是AJAX的工作方式(异步,如名称所示).该showGetResult函数在AJAX调用完成之前返回.showGetResult因此,只需返回,null因为这是你所分配的result.

success回调中移动任何依赖于AJAX调用结果的代码.或者,您可以使呼叫同步,但这通常不是您想要的.