简体   繁体   English

使用 AJAX 从 PHP 重新加载页面的一部分

[英]Using AJAX to reload part of a page from PHP

I have a webpage with a calendar that's created from PHP. I have a PHP function that creates the calendar (as a table) and returns it to the page to be inserted, like this:我有一个带有从 PHP 创建的日历的网页。我有一个 PHP function 创建日历(作为表格)并将其返回到要插入的页面,如下所示:

<?php
    $calendar = new date("Y-m-d");
?>
<html>
    ...
    <?=$calendar?>
    ...
</html>

I have a Calendar.php file with a __toString() method that gets called when I do.我有一个带有 __toString() 方法的 Calendar.php 文件,当我这样做时会调用该方法。 That __toString() method is the method that creates the calendar该 __toString() 方法是创建日历的方法

I know how to use AJAX to return the entire page but I'll like to just run the PHP function to recreate the calendar and send that to the page.我知道如何使用 AJAX 返回整个页面,但我只想运行 PHP function 来重新创建日历并将其发送到页面。 Currently, we change the month by recreating it in the backend and refresh the whole page to show the new month.目前,我们通过在后端重新创建月份来更改月份,并刷新整个页面以显示新月份。 I don't like the refreshing so that's why I want to do AJAX (or really anything I can use to refresh a part of the page without reloading the whole page).我不喜欢刷新,所以这就是为什么我想做 AJAX(或者我可以用来刷新页面的一部分而无需重新加载整个页面的任何东西)。 How can I run that PHP code and send that to the page without reloading the page?如何运行该 PHP 代码并将其发送到页面而不重新加载页面?

To clarify, on the page, I have a table with id="calendar".澄清一下,在页面上,我有一个 id="calendar" 的表。 There are other things on the page but the main thing is, the calendar has arrows to navigate to the previous month and the next month.页面上还有其他内容,但最主要的是,日历上有导航到上个月和下个月的箭头。 Currently, when you click on the arrows to either go to the next month or the previous month, the page is reloaded with the new month/date in the URL and our site gets the date from the query.目前,当您单击指向下个月或上个月的箭头 go 时,页面会重新加载 URL 中的新月份/日期,我们的网站会从查询中获取日期。 I want to refresh the calendar with the new month using AJAX or any other way to execute the PHP code and send it to the browser, all without having to reload the entire page.我想使用 AJAX 或任何其他方式来刷新新月份的日历,以执行 PHP 代码并将其发送到浏览器,而无需重新加载整个页面。 I hope this all makes sense.我希望这一切都有意义。

You can load the entire page using AJAX but its unnecessarily large amount of data.您可以使用 AJAX 加载整个页面,但它的数据量不必要地大。

You can just load the part you need: if there is a query string called 'calendar' or something you display only the calendar HTML. And you make a request to '?calendar' every minute or so.您可以只加载您需要的部分:如果有一个名为“日历”的查询字符串或您只显示日历 HTML 的内容。并且您每分钟左右向“?日历”发出请求。

This solution is not the best because you return plain HTML data.此解决方案不是最佳解决方案,因为您返回的是纯 HTML 数据。 You could make an endpoint which returns JSON data with the calendar data and you parse it in JS.您可以创建一个端点,它返回带有日历数据的 JSON 数据,然后在 JS 中解析它。

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

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