简体   繁体   English

使用 jQuery 加载外部网页

[英]Load external Web Page with jQuery

I was wondering what a good way to load an external web page (same server) would be.我想知道加载外部网页(同一服务器)的好方法是什么。 I have tried .load() and .get() however, The external page has a php script that spits out information every few seconds, the .load() and .get() only load it after the php is done.我尝试过 .load() 和 .get() 但是,外部页面有一个 php 脚本,每隔几秒就会吐出一次信息, .load() 和 .get() 仅在 php 完成后才加载它。 I have tried iFrame with does load it displaying the information being outputted by the PHP script.我已经尝试过 iFrame 并加载它以显示 PHP 脚本输出的信息。 However, I don't really like to use iFrames.但是,我不太喜欢使用 iFrame。 Thanks!谢谢!

If your goal is for the PHP information (that is spit out every few seconds) to be updated on your site, then what you want to do is use AJAX, inside a setInterval routine.如果您的目标是在您的站点上更新 PHP 信息(即每隔几秒输出一次),那么您想要做的是在 setInterval 例程中使用 AJAX。

See this post for the basics of AJAX -- it really is simpler than you might think. 有关 AJAX 的基础知识,请参阅这篇文章——它确实比您想象的要简单。 (You might first want to look at the simple examples linked at bottom). (您可能首先想查看底部链接的简单示例)。

Once you've got a simple ajax exchange happening, put that into a function called, for example, doAjax() -- and then create a setInterval, like this:一旦发生了简单的 ajax 交换,请将其放入一个名为doAjax()的函数中,然后创建一个 setInterval,如下所示:

setInterval('doAjax();',60000);

Here is an important note when considering setInterval 这是考虑 setInterval 时的重要注意事项


Following is a simple copy/paste(able) example that will let you see exactly what I mean:以下是一个简单的复制/粘贴(能够)示例,可以让您准确了解我的意思:

HTML/javascript: index.php HTML/javascript: index.php

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        
        <style>
            #timeDiv{width:40%;height:200px;background:wheat;padding:10px;}
        </style>
        
        <script type="text/javascript">
            $(document).ready(function() {

                doAjax();
                
                window.setInterval(function(){
                    doAjax();
                },2000);
                
            }); //END document.ready

            function doAjax() {
                $.ajax({
                    type: "POST",
                    url: "your_php_processor.php",
                    success: function(myData) {
                        $('#thetime').html(myData);
                    }
                });
            }

        </script>
    </head>

<body>

    <div id="timeDiv">
        The time is: <span id="thetime"></span>
    </div>

</body>

</html>

Now, the PHP side... your_php_processor.php现在,PHP 方面... your_php_processor.php

<?php

    $d = date("h:i:s");
    echo $d;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM