我正在尝试获取它,这样当按下按钮时,它就可以运行PHP函数,而无需重新加载页面。
我有这个按钮:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
<button>Reserve Book</button>
</div>
我想运行的:
<script>
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.post('reserbook.php', 'book_id');
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
});
</script>
PHP文件是reservebook.PHP:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['jqbookID']))
{
$bookID = $_POST['jqbookID'];
mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES
('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
}
?>
js运行良好,使模式框淡出,然后显示传递给它的变量,我只是不知道如何让帖子正常工作。
我一直在努力寻找其他问题的答案,比如从jquery调用php函数?以及如何将jQuery变量传递给PHP变量?
我也不确定一开始是否需要调用ajax特定的脚本,因为现在我只有
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
我的jquery。
这可能是一个非常简单的事情,一个新手的错误,所以我们感谢所有的帮助。
<script>
//called when button is clicked
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
//set parameter which you want to pass, url to be requested
$.ajax({ url: 'reserbook.php',
data: "book_id="+book_id,
type: 'post',
success: function(result) {
//after success it will be here and server have to send some data to be handled
alert(result);
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
您在reservebook.php
上发布了什么?book_id
是一个字符串。您应该将json或xml格式的数据发送到服务器,或者使用类似key1=value1&key2=value2
.$的查询。post是一个快捷函数,我认为最好使用$.ajax并指定类型属性POST
。
您必须向post函数添加一个参数才能在php 中获得postdata
{ jqbookID: book_id }
试试这个:
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.post('reservebook.php', { jqbookID: book_id }, function() {
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
});
});