如何在异步 PHP 回显(JavaScript 代码)发生时执行它们?

发布于 2024-11-02 16:45:09 字数 2342 浏览 0 评论 0原文

我有一个包含大约 100-150 个标记的自定义 Google 地图的页面。标记数据是通过外部 PHP 解析 XML 文件来获得的,该文件是事件/项目的列表,但每个事件中都有用于创建标记的适当数据。

目前一切正常,但加载地图需要一段时间,因为解析 XML 文件需要一些时间。为了加快速度,我本质上希望通过在页面加载时绘制空白地图来动态加载页面,然后运行外部 PHP 文件以使用 AJAX 异步解析 XML,并在从异步回显标记时将标记添加到地图中。 PHP 循环。

我不知道该怎么做,就是在这些回声出现时执行它们。

包含地图的页面 (explore.php) 运行 JavaScript:

 <script type="text/javascript">;
        function init() {
            // Draw the map (blank)
            var map_focus = new google.maps.LatLng(35,-37);
            var myOptions = { zoom: 2,center: map_focus,mapTypeId: google.maps.MapTypeId.ROADMAP };  
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            var xmlhttp = new XMLHttpRequest();
            // Run PHP to parse XML, asynchronously
            xmlhttp.open("GET","project_locations.php",true);
            xmlhttp.send();
            // This is where I want the JS/AJAX to execute echoes as they come from the above call to project_locations.php
            eval(xmlhttp.responseText);
        }
        // Add marker to map. Markers would appear as fast as the XML is parsed
        function addMarker(object, name, id) {
            google.maps.event.addListener(object,"click", function() {
                window.location = "showproject.php?id=" + id;
            });
        }
    </script>

这是 project_locations.php:

include('spparser.php'); // Parse XML
$i = 0;
foreach(SPParser::search($_REQUEST) as $index=>$sp) {
    if ($sp["latitude"] != '' && $sp["longitude"] != '') {
        echo "var marker" . $i . "= new google.maps.Marker({\n";
            echo "position: new google.maps.LatLng(" . $sp["latitude"] . ", " . $sp["longitude"] . "),\n";
            echo "map: map,\n";
            echo "icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/" . $sp["color"] . "-dot.png',\n";
            echo "title: \"" . $sp["name"] . "\"\n";
        echo "});\n\n";
        echo "addMarker(marker" . $i . ", \"" . $sp["name"] . "\", " . $sp["id"] . ");\n";
        $i++;
    }
}   

上面的代码绘制了一张空白地图,仅此而已。但是,如果我使用以下命令同步运行它:

xmlhttp.open("GET","project_locations.php",false);

有很长的延迟,则绘制地图和所有标记,这意味着 send() 之后的 eval() 语句将在最后执行所有回显。当它们由project_locations.php 回显时,如何实时执行它们?

I have a page with a custom Google Map that has about 100-150 markers. The marker data is obtained by parsing, via external PHP, an XML file which is a list of events/projects, but within each event is the appropriate data to create a marker.

Currently everything is working, but it takes awhile for the map to load because parsing the XML file is taking some time. To speed things up, I essentially want to load the page dynamically by drawing a blank map upon page load, then run the external PHP file to parse the XML asynchronously using AJAX and add the markers to the map as they are echoed out from the asynch. PHP loop.

What I don't know how to do is execute these echoes as they come.

The page that has the map (explore.php) runs the JavaScript:

 <script type="text/javascript">;
        function init() {
            // Draw the map (blank)
            var map_focus = new google.maps.LatLng(35,-37);
            var myOptions = { zoom: 2,center: map_focus,mapTypeId: google.maps.MapTypeId.ROADMAP };  
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            var xmlhttp = new XMLHttpRequest();
            // Run PHP to parse XML, asynchronously
            xmlhttp.open("GET","project_locations.php",true);
            xmlhttp.send();
            // This is where I want the JS/AJAX to execute echoes as they come from the above call to project_locations.php
            eval(xmlhttp.responseText);
        }
        // Add marker to map. Markers would appear as fast as the XML is parsed
        function addMarker(object, name, id) {
            google.maps.event.addListener(object,"click", function() {
                window.location = "showproject.php?id=" + id;
            });
        }
    </script>

And this is project_locations.php:

include('spparser.php'); // Parse XML
$i = 0;
foreach(SPParser::search($_REQUEST) as $index=>$sp) {
    if ($sp["latitude"] != '' && $sp["longitude"] != '') {
        echo "var marker" . $i . "= new google.maps.Marker({\n";
            echo "position: new google.maps.LatLng(" . $sp["latitude"] . ", " . $sp["longitude"] . "),\n";
            echo "map: map,\n";
            echo "icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/" . $sp["color"] . "-dot.png',\n";
            echo "title: \"" . $sp["name"] . "\"\n";
        echo "});\n\n";
        echo "addMarker(marker" . $i . ", \"" . $sp["name"] . "\", " . $sp["id"] . ");\n";
        $i++;
    }
}   

The above code draws a blank map and that's it. However, if I run it synchronously by using:

xmlhttp.open("GET","project_locations.php",false);

There is a long delay, then the map and all the markers are drawn, meaning the eval() statement that comes after send() executes all of the echoes at the end. How do I execute them in real-time as they are echoed by project_locations.php?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

若言繁花未落 2024-11-09 16:45:09

您可以使用 jQuery Ajax 执行异步 HTTP (Ajax) 请求。

您可以做的是,创建一个简单的 HTML 文件并在其中编写 JavaScript 函数,该函数将在一段时间超时后调用服务器方法,或者循环调用它或递归您的函数,无论您喜欢哪种。我可以看看你的问题的工作示例吗?以便我更好地帮助您?

You can use jQuery Ajax to perform an asynchronous HTTP (Ajax) request.

Exactly what you can do is, create a simple HTML file and write your JavaScript function there which will call the server methods after some timeout period or call it in loop or recurse your function, whichever you like. Can I see the working sample of your problem. So that I can assist you better?

烈酒灼喉 2024-11-09 16:45:09

由于 PHP 文件基本上生成 Javascript 代码,因此您可以将其作为 Javascript 文件包含在内。

使用 jQuery,您可以使用 $.getScript('project_locations.php')。它应该是异步的。

提示:当您从 PHP 生成 JS 变量时,请使用 PHP 函数 json_encode

As the PHP file is basically generating Javascript code, you could probably just include it as a Javascript file.

With jQuery you could do this with $.getScript('project_locations.php'). It should be asynchronous.

Tip: When you're generating JS variables from PHP, use PHP function json_encode.

無處可尋 2024-11-09 16:45:09

原因是脚本执行完成后会返回响应文本
要在下载时获取数据,您必须获取响应文本作为其下载。

while(true)
   {
    xmlhttp.onreadystatechange=function() //listens to the state chnages
   {
    if(xmlhttp.readyState==3) //if its still loading
     {
      eval(xmlhttp.responseText);
     }
   }

    if(xmlhttp.readyState==4) { eval(xmlhttp.responseText);} break; //finished loading get out of for loop
   }

还要确保 php 没有缓冲任何输出。像这样在你的文件顶部。

@ini_set('zlib.output_compression',0);
@ini_set('implicit_flush',1);
@ob_end_clean();

ob_implicit_flush(1);

The reason is that response text will be returned when script finishes execution
to get the data as its downloading you have grab the response text as its download, as such.

while(true)
   {
    xmlhttp.onreadystatechange=function() //listens to the state chnages
   {
    if(xmlhttp.readyState==3) //if its still loading
     {
      eval(xmlhttp.responseText);
     }
   }

    if(xmlhttp.readyState==4) { eval(xmlhttp.responseText);} break; //finished loading get out of for loop
   }

Also make sure that php is not buffering any output. as such on top of your file.

@ini_set('zlib.output_compression',0);
@ini_set('implicit_flush',1);
@ob_end_clean();

ob_implicit_flush(1);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文