【问题标题】:Updating a Table with Jquery and Ajax使用 Jquery 和 Ajax 更新表
【发布时间】:2014-11-25 10:37:07
【问题描述】:

我有一个相当大的页面,其中包含很多内容,其中一部分是日期价格表。通常,该表如下所示:

“上一个”和“下一个”链接以及日期选择器使用户能够在表格中显示不同的日期范围。然而,使用简单的 html 表单和 php/mysql,整个页面每次都会刷新,看起来很乱。我想使用 jQuery 和 Ajax 来刷新表格。

为此,我使用 PHP include() 将表放在一个单独的文件中。名为 calendar_inner.php 的单独文件使用名为 $startdate 的变量来执行必要的 mysql 查询以获取表的所有数据。现在我只需要了解如何使用 $startdate 的新值来提供包含的文件,然后刷新该文件。这就是我在黑暗中摸索 jQuery 的地方。

只从日期选择器开始,我已经开始编写 jQuery 脚本,但不出所料,它不起作用。

$('#StartDateCal').on('submit', function(g) { 
    g.preventDefault();  //prevent form from submitting
    var startdate = $("#StartDate").val();
    $.ajax ({
        type: 'post',
        url: 'calendar_inner.php',
        data: data,
        dataType: 'text'
    });
});

请对我温柔一点。我在 jQuery 上偶尔取得的成功仅限于我能够逐字逐句复制他人代码的情况。谢谢。

编辑 我已经根据 Raslett 的建议修改了我的脚本,但我还没有找到解决方案。

$('#StartDateCal').on('submit', function(g) { 
    g.preventDefault();  //prevent form from submitting
    $.ajax ({
        type: 'post',
        url: 'calendar_inner.php',
        data: $('#StartDateCal').serialize(),
        success: function(result) {
            $('#getresult').html(result);
        }
    });
});

现在整个页面没有刷新,只有 calendar_inner.php 文件,所以有点成功。我认为现在的问题是如何处理结果。使用上面的代码并放置

<div id="getresult"></div>

在 calendar_inner.php 的开头将我的 404 错误页面插入到整个页面中。将 html(result) 更改为 text(result) 会将 404 错误页面的整个代码写入同一空间。我不知道导致服务器调用 404 错误页面的脚本正在生成什么。

第二次编辑 我摆脱了 404 错误。我叫错了网址。现在已经纠正了,我越来越近了,但剩下的事情很神秘。该脚本现在将表格的第一行写入两次:一次的开始日期为 1 月 1 日,第二次的开始日期为原始开始日期。所以现在我要做的就是: 1.说服第一版表格行使用新的开始日期 2.停止显示第二个版本的表格行 3. 将开始日期传递到计算和写入价格的表格的下一部分 呸!不容易。

第三次编辑 正如 Rasclatt 所说,jQuery 现在正在工作,我只需要整理 calendar_inner.php 文件。为简单起见,我只是将前几行放在下面。关键变量是 $startdate,然后它会驱动其他所有内容。我需要 jQuery 来更改 $startdate 的值。

第四次编辑 更新了 calendar_inner.php 的代码并显示了更多内容。见下文。

<div id="getresult"></div>
<script>
$(document).ready(function() {
//Submit change of date in price tab without refreshing page
$('#StartDateCal').on('submit', function(g) { 
        g.preventDefault();  //prevent form from submitting
        $.ajax ({
            type: 'post',
            url: '/includes/calendar_inner.php',
            data: $('#StartDateCal').serialize(),
            success: function(result) {
                console.log(result),
                $('#getresult').html(result);
            }
        });
    });
});
</script>
<?php
if(isset($_POST['StartDate']) && !empty($_POST['StartDate'])) {
            $startdate  =   htmlentities($_POST['StartDate'], ENT_QUOTES);
            $firstdate  =   date('Y-m-d',$startdate);
            $lastdate   =   date('Y-m-d',strtotime('+11 days',strtotime($firstdate)));

            // database insertion of above variables
        }else{
            $firstdate = date('Y-m-d',$startdate);
$lastdate = date('Y-m-d',strtotime('+11 days',strtotime($firstdate)));
        }

//Select database
require_once('../Connections/MySQL.php');
mysql_select_db($database_MySQL, $MySQL);
mysql_set_charset("utf8");

// Create a temporary table
$query_temptable = "CREATE TEMPORARY TABLE temptable (dt DATE NOT NULL)";
$result = mysql_query($query_temptable, $MySQL) or die(mysql_error());

//Now loop through the date range and fill the temporary table
$thisdate = $firstdate;
while (strtotime($thisdate) <= strtotime($lastdate)){
$query_insertdate = "INSERT INTO temptable (dt) VALUES ('$thisdate')";
$result2 = mysql_query($query_insertdate, $MySQL) or die(mysql_error());
$thisdate = date('Y-m-d', strtotime('+1 day', strtotime($thisdate)));
}

// MySQL query to get price_id (or blank) for all dates in range
$query_tariff = "SELECT temptable.dt, lh_dates.tariff_id FROM temptable LEFT JOIN lh_dates ON temptable.dt = lh_dates.dt AND hid = '$hid'";
$tariff = mysql_query($query_tariff, $MySQL) or die(mysql_error());

// Create array of tariff_ids
$i = 0;
$tariff_id_list = array();
while ($row_tariff = mysql_fetch_assoc($tariff)) {
$tariff_id_list[$i] = $row_tariff['tariff_id'];
$date_list[$i] = $row_tariff['dt'];
$i++;
}
$tariff_id_unique = array_unique($tariff_id_list);

// Drop the temporary table
$query_droptable = "DROP TEMPORARY TABLE IF EXISTS temptable";
$result3 = mysql_query($query_droptable, $MySQL) or die(mysql_error());

//Here we start building the pseudo-table using divs 
echo "<div class='calendar'>";
// Dates row
echo "<div class='toprow'>"; 
echo "<div class='cal_firstcol'>&nbsp;</div>";
$i = 0;
$thisdate=strtotime($firstdate);
while ($i++ < 12) {
$day_week = date('D', $thisdate); 
$day_num = date('j', $thisdate);
$month_name = strtoupper(date('M', $thisdate));
echo "<div class='cal_dates'>";
echo $day_week."<br><span class='cal_day'>".$day_num."</span><br>".$month_name;
$thisdate = $thisdate+86400;
echo "</div>"; 
}
echo "<div class='clear'></div></div>";

// Room rows
//MySQL query to get rooms
$query_room = "SELECT room_id, roomtype, normalocc, singleocc, extrabed, childbed, cot FROM lh_rooms WHERE hid = '$hid' ORDER BY orderr ASC";
$room = mysql_query($query_room, $MySQL) or die(mysql_error());
while ($row_room = mysql_fetch_assoc($room)) {
foreach ($tariff_id_unique as $value) {
$tariff_id = $value;
$room_id = $row_room['room_id'];
$query_price = "SELECT * FROM lh_prices WHERE tariff_id = '$tariff_id' AND room_id = '$room_id'";
$price = mysql_query($query_price, $MySQL) or die(mysql_error());
$row_price[$value] = mysql_fetch_assoc($price);
}

echo "<div class='row'>"; 
echo "<div class='cal_firstcol'>".$row_room['roomtype']."</div>";
$thisdate = $firstdate;
$i=0;
while (strtotime($thisdate) <= strtotime($lastdate)){
$thisday = strtolower(date('D',strtotime($thisdate)));
echo "<div class='cal_pricecol'>";
if (in_array($thisday, $we_rates)) {
echo $row_price[$tariff_id_list[$i]]['price_we_std'];   
}else{
echo $row_price[$tariff_id_list[$i]]['price_wd_std'];
}
echo "</div>";
$i++;
$thisdate = date('Y-m-d',strtotime('+1 day',strtotime($thisdate)));
}
echo "</div>";

if (($row_room['extrabed']>=1)||($row_room['childbed']>=1)) {
echo "<div class='row hiddenrow' style='display:none'>"; 
echo "<div class='cal_firstcol'>Child Extra Bed</div>";
$thisdate = $firstdate;
$i=0;
while (strtotime($thisdate) <= strtotime($lastdate)){
$thisday = strtolower(date('D',strtotime($thisdate)));
echo "<div class='cal_pricecol'>";
echo $row_price[$tariff_id_list[$i]]['price_eb_c']; 
echo "</div>";
$i++;
$thisdate = date('Y-m-d',strtotime('+1 day',strtotime($thisdate)));
}
echo "<div class='clear'></div></div>";
}

}

echo "</div>"; 
?>

第五次编辑 (!) 作为对 Rasclatt 的回复,这是脚本运行后表格的样子。 datepicker、Previous、checkbox 和 Next 都在父页面中。从 9 月 30 日开始的第一行日期是脚本的结果,第二行日期编码到 calendar_inner.php。搬家

<div id="getresult"></div>

页面进一步向下移动日期的第一行。 日期选择器的表单代码是

<form id="StartDateCal">
<input type="hidden" name="hid" id="hid" value="<?php echo $hid ?>">
<input type="hidden" name="lang" id="lang" value="<?php echo $$ln ?>">
From <input name="StartDate" id="StartDate" class="datebox" size="10" value="<?php echo date('j M Y', $startdate) ?>" type="date"> 
<input name="submit" class="button" id="CalSubmitBtn" type="submit" value="Go">
</form>

【问题讨论】:

  • 另外,我在代码中删除&lt;div id="getresult"&gt;&lt;/div&gt; 的唯一原因是向您显示反馈。您可以将反馈指向任何容器。
  • 谢谢拉斯克拉特。我现在把 calendar_inner.php 放进去。
  • 最初 $startdate 在父文件中设置为“今天”。然后表单通过 jQuery 发送一个新值,该值需要传递到 $startdate。
  • 您是否考虑过使用众多优秀的基于 jQUery 的表格数据插件之一来为您处理客户端部分?
  • 迈克·布兰特。不,我没有考虑过插件。我刚刚看了一些,但我没有看到任何我想要的东西。也许一些更全面的可以,但需要时间才能找到,更多的时间来设置 ip,然后我会得到很多没有被使用的代码。

标签: php jquery mysql ajax


【解决方案1】:

这应该加载表单,然后是通过 AJAX 将表格自动加载到 &lt;div id="get result"&gt;&lt;/div&gt; 容器中的脚本。提交表单后,它应该加载到覆盖表格的同一位置。因此,为了澄清,您不会运行任何 php 来在原始加载页面上构建表。运行 php 的目的就是计算 $hid$$ln$startdate。您的calendar_inner.php 将仅包含日历代码,加载页面将仅包含表单和 jQuery。

作为一个选项,我向CheckDates(FetchResults) 添加了一个首选项,其中FetchResults 是容器的名称。以防万一您想将其加载到其他容器名称中。

<form id="StartDateCal">
<input type="hidden" name="hid" id="hid" value="<?php echo $hid ?>">
<input type="hidden" name="lang" id="lang" value="<?php echo $$ln ?>">
From <input name="StartDate" id="StartDate" class="datebox" size="10" value="<?php echo date('j M Y', $startdate) ?>" type="date"> 
<input name="submit" class="button" id="CalSubmitBtn" type="submit" value="Go">
</form>
<div id="getresult"></div>
<script>
    function CheckDates(FetchResults)
        {
             $.ajax ({
                type: 'post',
                url: '/includes/calendar_inner.php',
                data: $("#StartDateCal").serialize(),
                success: function(result) {
                 $("#"+FetchResults).html(result);
                }
            });
        }
    $(document).ready(function() {
        // Auto load ajax
        CheckDates('getresult');
        // On submit load ajax
        $('#StartDateCal').submit(function() {
            // Add a loader image or text so you know it's refreshing
            $('#getresult').html("Loading...");
            // Run table loader
            CheckDates('getresult');
            return false;
        });
    });
</script>

【讨论】:

  • 是的,表格是 id="StarteDateCal"。我没有使用序列化,因为我认为当我只传递一个变量时没有必要。但是,我的代码中有一点手指错误,因为“数据”应该是“开始日期”。我已经使用您建议的代码取得了一些进展,但还没有。有关更多信息,请参阅我对原始帖子的编辑。
  • 不,它不是字面上说的“今天”。也许我应该说它等于“time()”。我看到你的 calendar_inner.php 代码来自哪里,但它还不在那里。我意识到 datepicker 的名称和 ID 为 StartDate,因此我更改了您的 $_POST 变量以适应。但是,当我使用 datepicker 更改 startdate 时,我仍然得到两个日期行:第一个从 1 月 1 日开始,第二个从 10 月 1 日(今天)开始。我将使用更多的 calendar_inner.php 代码对我的原始问题进行另一次编辑。
  • 自从上面的第四次编辑以来,我一直在摆弄以试图了解发生了什么。我现在从 console.log 中发现(结果)包含 div、脚本和带有新日期的表的第一行。这就解释了为什么我得到两行日期:第一行是新的,然后是旧的。我怎样才能在(结果)中获得 $startdate 的新值?
  • Rasclatt,我刚刚添加了表格的视觉效果,因为它在运行脚本后看起来,以及表格的代码。 (我不确定你想看哪个。非常感谢你在这方面的耐心等待。
猜你喜欢
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 2012-05-12
  • 2013-06-27
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 2018-08-12
相关资源
最近更新 更多