我的页面上有一个按钮:
<button class="play"></button>
当我点击它时,它会通过 jQuery 启动视频
$('.play').on('click',function(){
player.play();
});
但是我还想添加 PHP 代码以在他单击该按钮时将用户 ID 保存在数据库中。
如何混合 PHP 和 jQuery?我不习惯 Ajax,这是解决方案吗?
谢谢你的帮助!
添加一个功能:
function add_to_db(user_id){
$.post('add.php', {userId: user_id}, function(response){
//do something with the response
r = JSON.parse(response);
if (r.status === 'error'){
//handle the error
alert(r.message);
}
});
});
当你玩时,请执行以下操作
$('.play').on('click',function(){
player.play();
user_id = //however you chose to set this in the page
add_to_db(user_id);
});
你的 add.php:
//perform your db update or insert
//if successful:
$response['status'] = 'success';
//else:
$response['status'] = 'error';
$response['message'] = 'update was not successful';
//look into try/catch blocks for more detailed error messaging.
//then send the response back
echo json_encode($response);
尝试使用ajax
$('.play').on('click',function(){
player.play();
$.ajax({
type: "POST",
url: "some.php", // your php file name
data:{id :"id"}, //pass your user id
success:function(data)
{
if(data==true)
alert("success");
else
alert("error");
}
});
}
<?php
$success=false; //Declare and initialize a variable
// do your code to update your database
//and check if the database is updated , if so set $success=true
echo $success;
?>