【发布时间】:2017-02-21 06:20:43
【问题描述】:
我正在尝试使用 jQuery ajax api 从 mysql 数据库中检索数据。我正在使用的 SQL 查询工作正常,因为我通过创建用户表单和传统上$_POSTing 其内容来测试它是否从我的数据库中检索到正确的数据。
但是,我现在想从我的 mysql 表中检索数据,而不必使用 jQuery ajax 函数重新加载页面。我是 jQuery 的新手,我以前没有用过很多,如果有人能给我提供一个很好的例子来说明它是如何工作的,我将非常感激。我在网上查看了各种文章和指南,但我无法理解。
这是一个表格:
<form id="restaurant_reservation">
<label for="date">Reservation Date?</label>
<input type="text" name="date" id="date" value="yyyy-mm-dd" />
<label for="capacity">Amount of Customers?</label>
<input type="text" name="capacity" id="capacity" />
<label for="license">Smoking or Non-Smoking Area?</label>
<select id="license">
<option value="0" id="no">Smoking</option>
<option value="1" id="yes">Non-Smoking</option>
</select>
</form>
这里是php代码:
<?php
$user_reservation_date = $_POST['user_date'];
$user_customer_amount = $_POST['customer_amount'];
$user_smoking_non_smoking = $_POST['user_smoking_selection'];
$my_query = "SELECT * FROM restaurant
WHERE $user_reservation_date = date_available
AND $user_customer_amount >= max_seating
AND $user_smoking_non_smoking = smoking_choice";
$result =& $db->query($my_query);
if (PEAR::isError($result)) {
die($result->getMessage());
}
echo '<div id="output">';
echo'<table">';
echo '<th>restaurant name</th>';
echo '<th>Max Customer Seating</th>';
echo '<th>Smoking or Non Smoking</th>';
echo '<th>Average price per head</th>';
while($row =& $result->fetchRow()) {
echo '<tr>';
echo '<td>'.$row['rest_name'].'</td>'
echo '<td>'.$row['max_seating'].'</td>'
echo '<td>'.$row['smoking_choice'].'</td>'
echo '<td>'.$row['avg_price_per_head'].'</td>'
echo '</tr>';
}
echo '</table>';
?>
这是我对 jquery 代码的尝试:
$(function(){
$('#date').keyup(function(){
var user_input= $('#date').val();
});
});
$(function(){
$('#date').keyup(function(){
var user_input1=$('#date').val();
$.ajax({
type: 'POST',
data: ({user_date : user_input1}),
url: 'search.php',
success: function(data) {
$('#output_div').html(data);
}
});
});
});
我使用相同的代码,但更改了表单中其他两个字段的#values。
我想使用 jQuery ajax 来获取此表单的输入和选定值,并将它们存储在我的 php 文档中的一个变量中,这样我就可以在我的 sql 查询中使用用户表单数据来检索适当的餐馆。
我真的很想学习如何做到这一点,我真的很感激任何帮助。非常感谢您的阅读。如果我在正确描述我的问题时含糊不清,我很抱歉。谢谢。
【问题讨论】:
-
您阅读过
jquery.ajax文档吗? api.jquery.com/jQuery.ajax -
嗨,是的,我一遍又一遍地阅读它,但我很难掌握它的概念。在我看来,为了理解他们的文档,你必须对 jquery 有一定的了解。你能帮帮我吗?谢谢。
-
here 你去吧,这应该证明是有用的 :) 首先点击谷歌“jquery ajax 初学者教程”