dongzhong1891 2014-05-15 19:21
浏览 47
已采纳

如何从ajax立即加载PHP?

I am trying to directly load a page using ajax. Here are the details:

HTML:

<div id="feedback"> </div>
<script type="text/javascript" src="script.js"></script>

script.js:

$(document).ready(function() {
    $.ajax({
        url: 'do.php',
        success: function(data){
            $('#feedback').html(data);
    });
});

do.php:

<?php
    //Do whatever...
    echo "Done!";
?>

What I am seeing is: the page first loads, and there is a delay before the "feedback" div gets written. How can I solve this?

  • 写回答

2条回答 默认 最新

  • douzi9744 2014-05-15 19:35
    关注

    As far as I know of course it will have that delay. Suppose your page containing <div id="feedback">[…]</div> is loaded at 0th second now:

    $(document).ready(function() {
        $.ajax({
            url: 'do.php',
            success: function(data){
                $('#feedback').html(data);
        });
    });
    

    Is called as apparently it’s visible when document loads. So suppose its called at 3rd second when the document is ready—you can refer to this page for details—now you will be seeing that feedback div blank for 3 seconds.

    I can suggest 2 things:

    1. You can place a loader image by default inside the div so your code will change to <div id="feedback"><img src='loader.gif'></div> (Assume you have the loader.gif in the same directory of the page). By doing this you will make the user visually understand that some processing is going on and will load data.

    2. Instead if you can place file_get_contents() or include() so it will look something like this <div id="feedback"><?php file_get_contents('do.php');?></div> or <div id="feedback"><?php include('do.php');?></div> As far as I know file_get_contents will execute the page and then load while include will load and then execute hence in include() you have the variables in the page available whereas in file_get_contents are not available but CSS would work in both cases.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集