繁体   English   中英

单击按钮时使用PHP + jQuery

[英]Use PHP + jQuery when click on a button

我的页面上有一个按钮:

<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");
    }
    });
    }

some.php

<?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;


?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM