我正在构建一个如下所示的页面:
目标是什么:
- 当用户点击输入框并选择特定日期时,它会运行一个 PHP 脚本,在数据库中搜索具有该特定日期的记录,并将它们附加到特定的 div 中。
到目前为止我做了什么:
- HTML 和 CSS:
<div class="input-group col-md-8 col-sm-8 col-xs-8"> <input type="text" class="form-control date"> <span class="input-group-addon calendar-date-picker"> <i class="glyphicon glyphicon-calendar"></i> </span> </div>
(...)
this is cool :<p> <?php print_r($_POST);?> </p> <div class="results-ajax"></div>
。 它在输入类中使用“日期”来打开日期选择器日历。
。 它有一个带有“results-ajax”类的特定 div,其中脚本生成的输入应显示在。
- JS 和 Ajax:
jQuery(function($) { $(".date").datepicker({ onSelect: function(dateText) { display("Selected date: " + dateText + "; input's current value: " + this.value); $(this).change(); } }).on("change", function() { display("Got change event from field"); $.ajax({ type: "POST", url: 'events_script.php', data: ({dates: this.value}), success: function(data) { $(".results-ajax").load(data); alert(data); } }); }); function display(msg) { $("<p>").html(msg).appendTo(document.body); } });
。 选择新日期后,结果将显示在“结果”下。 .
。 Ajax 调用正在 events_script.php 中发布。
- PHP(events_script.php)
<?php include 'config/config.php'; include 'libraries/database.php'; if ($_SERVER['REQUEST_METHOD'] == 'POST') { print_r($_POST); echo $_POST[dates]; $dias= $_POST[dates];
//Make database query
$sql = "SELECT * FROM events RIGHT OUTER JOIN companies ON companies.companyID = events.Ref_ID WHERE events.Start_Date= '$dias%' ORDER BY events.Start_Date DESC"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) { echo '<p>'.print_r($_POST).'</p>'; }
} else { echo 'No results found.'; } } ?>
结果:
1.JS显示结果并追加
2. Ajax 中警报的结果(使用 PHP 脚本):
问题:
- 为什么警报数据没有按照 Ajax 中的命令加载到带有“results-ajax”类的 div 中?
我也测试过使用appendTo而不是load,但也不起作用。
另外,
- 。为了使发布的数据在查询(“$dias%”)中能够被数据库识别,过程中是否缺少/错误任何步骤?
因为 rn 显示“未找到结果”(正如您在警报中看到的那样),并且数据库中存在具有该特定日期的记录。
(这种情况发生了很多次,该值与数据库中的值完全相同,但因为一个是字符串,另一个是日期,所以没有显示任何内容 - 只是为了确保这不是其中一种情况)
注意:
PHP 错误日志中没有错误。
在控制台中,出现以下错误:GET example.com/Array( 404 (Not Found)。一旦警报框关闭,它就会显示。
最佳答案
您需要将日期转换为 MySql 格式,具体操作方法如下:
function date_convert($value,$fromFormat,$toFormat){
try{
$myDateTime = DateTime::createFromFormat($fromFormat, $value);
if ($myDateTime)
return $myDateTime->format($toFormat);
} catch (Exception $ex) {
return '';
}
}
// this supposes that by 01/03/2017 you're talking about the 1st of Mars
// if you mean the 3rd or January change the from format to : 'm/d/Y'
$dias = date_convert($dias,'d/m/Y','Y-m-d');
关于javascript - Ajax、PHP 和 MySQL 以及在页面中附加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41908768/