变量值没有传入Bootstrap Modal中的mySQL语句

时间:2014-06-15 20:39:34

标签: javascript php jquery html twitter-bootstrap

我通过span标签使用jQuery将变量传递给Bootstraps模式但在模式中运行PHP时遇到问题。这些变量都是正常的,但是当我尝试运行mySQL语句时,我存储在变量中的span标记看起来没什么,即使它很好。我给出了以下代码的示例:

HTML:

<a role='button' data-topicid='$number' data-toggle='modal' data-target='#modaluserinfo' class='modalsend'>

JS:

<script>
$(document).ready(function () {
$('.modalsend').click(function () {
$('span.user-topicid').text($(this).data('topicid'));
});
}); 
</script>

模态:

<div class="modal fade" id="modaluserinfo" tabindex="-1" role="dialog" aria-labelledby="modaluserinfo" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Details...</h4>
</div>
<div class="modal-body" style="text-align:center; margin-top:10px;">
<?php 
$numberid = "<span class='user-topicid'></span>";
echo $numberid;// THE VALUE ECHOS FINE IN THE MODAL, BUT FAILS TO LOAD IN THE MYSQL QUERY BELOW

$sqlcomment = mysql_query("SELECT * FROM comments WHERE comments.topic_id='$numberid' AND comments.emotions_id='1'");
$commentnumber = mysql_num_rows($sqlcomment);

echo $commentnumber;
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

我的猜测是PHP语句在页面加载时运行,而不是在打开模态并将变量发送到span标记时运行。不太确定如何解决这个问题。

2 个答案:

答案 0 :(得分:0)

PHP仅在服务器上运行。要使Javascript或jQuery执行PHP脚本,需要调用服务器。 GET(如链接)和POST(如表单)有两种方法。你有两种GET和POST方式,一种方法是重新加载页面,另一种方法是XHR对象,AKA Ajax。

因此,制作一个单独的PHP文件,例如......

get_number_comments.php:

<?php

// LOAD YOUR DATABASE CREDENTIALS HERE

$numberid = mysql_real_escape_string($_GET['topicid']);
$page = mysql_real_escape_string($_GET['page']);

$sqlcomment = mysql_query("SELECT * FROM comments WHERE comments.topic_id='$numberid' AND comments.emotions_id='1'");
$commentnumber = mysql_num_rows($sqlcomment);

echo $commentnumber;

?>

将文档就绪功能更改为:

$(document).ready(function () {
    $('.modalsend').click(function () {
        $('span.user-topicid').load('get_number_comments.php?topicid=' + $(this).data('topicid') + '&page=' + encodeURIComponent('<?php echo page; ?>'));
    });
});

你的模态的内部DIV现在看起来像:

<div class="modal-body" style="text-align:center; margin-top:10px;">
    <span class='user-topicid'></span>
</div>

jQuery的加载函数对服务器进行XHR调用,在这种情况下执行您在第一个参数get_number_comments.php中输入的文件。那么get_number_comments.php接受GET变量,安全地转义它,在查询中插入它,并通过XHR对象将结果发送回页面。

(顺便说一下,由于PHP mysql_*函数显然是无效的,我要求你转换为PHP mysqli_*函数。然后你也可以使用严格的数据库安全措施。)

答案 1 :(得分:0)

使用以下方法传递多个变量已解决问题:

HTML:

$page = mysql_real_escape_string($_GET['page']);

<a role='button' data-topicid='$number' data-page='$page' data-toggle='modal' data-target='#modaluserinfo' class='modalsend'>

jQuery的:

$(document).ready(function () {
$('.modalsend').click(function () {
$('span.user-topicid').load('get_number_comments.php?topicid=' + $(this).data('topicid') + '&page=' + $(this).data('page'));
});
});

有关更多详情,请参阅@bloodyKnuckles帖子