jQuery 无法直接使用 PHP 会话,您需要进行 ajax 调用。
尝试这个。
解释:
- 这将捕获链接内的值,发布到 PHP 文件并在“结果”div 中打印数据而不刷新页面。
(不要忘记在帖子末尾阅读我的观察)
HTML:
<a href='#' id='country'>USA</a>
<br/>
<div id="result"></div>
JS:
$('#country').click(function(){
// get the value inside the <a> tag
var country = $(this).html();
$.post('process.php', { country:country }, function(data){
// Everything is Ok, so data won't be 0
if(data != 0){
// Print country information
$('#result').html(data);
}
});
});
进程.php
<?php
if($_POST() && isset($_POST['country'])){
/* Connect to DB */
$link = mysql_connect('server', 'user', 'pwd');
if (!$link) {
// No connection
print(0);
exit();
}
$db = mysql_select_db('db', $link);
if (!$db) {
// DB selection error
print(0);
exit();
}
/* sanitize the value */
$country = mysql_real_escape_string($_POST['country']);
/* do your query */
$sql = "SELECT * FROM country WHERE country_name = '$country'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
// At this point I am supposing that you stored in your table
// latitudes and longitudes of countries.
echo "Latitude is: ".$row['latitude']." Longitude is: ".$row['longitude'];
}
} else {
// No results found
print(0);
}
}
?>
观察:
例如:
如果我有:
<a href='#' id='country'>United States of America</a>
在 SQL 查询中,我将拥有:
SELECT * FROM country WHERE country_name = 'United States of America';
更好的方法可能是:
<a href='#' id='us'>United States of America</a>
因此,在我的 JS 中,我将不得不为此替换 var country = $(this).html();
:
//outputs 'us'
var country = $(this).attr('id');
然后在你的 SQL 查询中你会得到这个:
SELECT * FROM country WHERE country_name = 'us';
使用代码而不使用名称更合理(名称只是为了向用户展示,以便更好地理解,因为这样您将有更多问题来清理在查询中使用它的值,并且还使用诸如trim();
删除空格和其他功能之类的功能) . 如果这样做,您将不得不更改查询以通过代码查找国家/地区:
SELECT * FROM country WHERE country_code = 'us';
希望这可以帮助 :-)