[英]Get data from MySQL using AJAX
I need to take an input (date) from a form in a php file, and use the date variable to select data from a mysql database and return an array in the same php file without refreshing the page. 我需要从php文件中的表单中获取输入(日期),并使用日期变量从mysql数据库中选择数据并在同一个php文件中返回一个数组而不刷新页面。 Right now, I have 3 files:
index.php
, global.js
, and date.php
现在,我有3个文件:
index.php
, global.js
和date.php
index.php
takes an input (a date, in this case) index.php
接受输入(在这种情况下为日期)
Date: <input type="text" id="date">
<input type="submit" id="date-submit" value="Submit">
<div id="date-data"></div>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="js/global.js"></script>
global.js
listens for a click on the submit button and posts the input (date) to date.php
global.js
侦听提交按钮上的单击并将输入(日期)发布到date.php
$('input#date-submit').on('click', function() {
var date = $('input#date').val();
$.post('../ajax/date.php', {date: date}, function(data) {
$('div#date-data').html(data);
alert(data);
});
});
date.php
takes the date and queries the mysql database to return an array. date.php
获取日期并查询mysql数据库以返回数组。 This array needs to be passed back to index.php
but I can't figure out how to do it. 这个数组需要传递回
index.php
但我无法弄清楚如何做到这一点。
<?php
$con = mysql_connect('localhost', 'root', 'pass');
mysql_select_db('gymflow', $con);
$date = $_POST['date'];
$query = mysql_query("SELECT * FROM table WHERE `date` = $date");
$values = array();
while ($row = mysql_fetch_array($query))
{
$values[] = $row['utilization'];
}
echo json_encode($values);
?>
Ideally, I need to be able to have the $values
variable from date.php
passed to a $values
variable in index.php
理想情况下,我需要能够有
$values
从变量date.php
传递到$values
变量index.php
There must be an easier way to do this... 必须有一个更简单的方法来做到这一点......
The purpose of your AJAX call is to not refresh index.php
, and instead deliver the result of data.php
straight into the first page. AJAX调用的目的是不刷新
index.php
,而是将data.php
的结果直接传递到第一页。 You can modify the DOM via the javascript callback, and should make other database-requests in data.php
. 您可以通过javascript回调修改DOM,并在
data.php
创建其他数据库请求。 There is no purpose in letting index.php
aware of the output of data.php
, simply because when the Javascript call is made, your first page has already been processed and sent to the client and possibly already rendered in the browser window. 让
index.php
意识到data.php
的输出没有任何意义,因为当进行Javascript调用时,您的第一页已经被处理并发送到客户端并且可能已经在浏览器窗口中呈现。
If you need to know the input value in subsequent requests to index.php
you may store in the value in the user's session. 如果您需要知道对
index.php
后续请求中的输入值,您可以将其存储在用户会话的值中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.