簡體   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