本文介绍了从数据库+ AJAX + PHP加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个关于从数据库加载多个领域,并利用它们在JavaScript的问题。
I have a question about loading multiple fields from the database and use them in javascript.
这是我的表死亡与字段:
This is my table "deaths" with fields:
- district
- year_1999
- year_2000
- year_2001
- year_2002
- year_2003
- year_2004
- year_2005
- year_2006
- year_2007
- year_2008
- year_2009
现在我要加载的字段一年_....时区='districtname
Now I want to load the fields year_.... when district = 'districtname'
这是我有什么:(PHP)
This is what I have: (PHP)
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "testdatabase";
$tableName = "deaths";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT year_1999,year_2000,year_2001,year_2002,year_2003,year_2004,year_2005,year_2006,year_2007,year_2008,year_2009 FROM $tableName WHERE district = 'Binnenstad'"); //query
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
JavaScript的:
Javascript:
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: './api4.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
for (var i in rows)
{
var row = rows[i];
var data = row[0];
$('#districts ul').append("<li>" + data + "</li>")
.append();
}
}
});
});
但是,这只能显示第一列数据(year_1999)。
But this only shows the first column data (year_1999).
我该如何解决这个问题?
How can I fix this?
推荐答案
而不是的(VAR我行)...
尝试:
更新。寻找你的PHP接近试试像
此画每年:
UPDATE. Looking your php closer try something like
this to draw each year:
$.each(rows, function(i, data) {
$.each(data, function(j, year) {
$('#districts ul').append("<li>" + year + "</li>")
});
});
这篇关于从数据库+ AJAX + PHP加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!