我正在尝试使用jquery / php / mysql创建一个应用程序。它应该首先列出数据库中的所有商店,并且工作正常。但是,当您单击一个时,您应该获得有关该特定商店的更多信息。这就是问题出现的地方。
基本上,如果我想从数据库中获取所有行,一切正常。但是,当我尝试使用查询字符串来选择特定行时,它不起作用。我已经尝试了很多东西,我已经看到我的php文件中的$ _GET使得jquery函数中断并且根本不输出任何东西。即使我只对GET做了回音,它也会打破它。我无法理解为什么。如果我只是“选择*其中id = 2”就可以了。但是在使用GET获取2的查询字符串时不是这样。
(另外,现在这只是JSON,但后来我当然需要jsonp的跨域)
这是我的PHP代码:
<?php
// Settings for accessing the DB.
$host = "localhost";
$db = "mappdb";
$username ="db-username";
$password ="******";
// Connect and query the DB and get the data for all attractions
$connect = mysql_pconnect($host, $username, $password) or die("Could not connect to the database");
mysql_select_db($db) or die("Could not select the database");
$arr = array();
$idnumber = $_GET["pid"];
$result = mysql_query("select * from attractions where id = $idnumber");
while($object = mysql_fetch_object($result)) {
$arr[] = $object;
}
echo '{"attractions":'.json_encode($arr).'}';
?>
这是我的jquery:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="jquery.mobile-1.3.1.min.css" />
<script src="jquery-1.9.1.min.js"></script>
<script src="jquery.mobile-1.3.1.min.js"></script>
<title>Store Finder</title>
</head>
<body>
<div data-role="page" id="page">
<div data-role="header" data-position="fixed">
<a href="index.html" data-icon="back">Back</a>
<h6>Search</h6>
</div>
<div data-role="content">
<ul data-role="listview" data-filter="true" id="listed" data-filter-placeholder="Filter cities or stores..." data-inset="true">
<script type="text/javascript">
$(document).ready(function(){
var url="http://localhost/mapp/json.php?pid=2";
$.getJSON(url,function(json){
// loop through the stores here
$.each(json.attractions,function(i,dat){
$("#listed").append(
'<li><a href="viewstore.html?id='+dat.id+'">'+dat.id+' '+dat.name+'</a></li>'
).listview('refresh');
});
});
});
</script>
</ul>
</div>
<div id="msg"> </div>
<div data-role="footer" data-position="fixed">
<h6>Footer</h6>
</div>
</div>
</body>
</html>
一直坐在这一整天都不能为我的生活弄清楚。非常感谢一些帮助。谢谢!
答案 0 :(得分:2)
首先,您的代码存在一些非常重要的安全问题
$_GET['pid']
,这会使您的应用容易受SQL Injections攻击。
请参考谷歌搜索对策并尽快解决此问题!最有可能在于$.getJson()
首先,我要确保?pid=2
- 部分确实附加到您的网址,方法是查看您的浏览器Firebug /开发人员工具的网络标签,以查看被调用的网址。
我认为它完全省略了pid
这可以通过调用这样的函数来解决:
var url = "http://localhost/mapp/json.php
var data = { 'pid': 2};
$.getJSON(url, data, function(json) {
...
});
根据$.getJSON() manual,这个函数需要3个参数。
首先是url,第二个是普通数据对象,第三个是成功时的回调函数。
data
将被视为查询参数列表,这些参数已经过urlencoded并附加到您的网址。