簡體   English   中英

AJAX 發送公共 static function

[英]AJAX send public static function

我想在數據庫中插入一個like ,但我想在多個頁面上這樣做。 我創建了一個頁面,我在其中插入了likes ,並將此頁面包含在所有其他頁面中。 它有效,但現在每次我like時,頁面都會重新加載。 我想我可以用 AJAX 解決這個問題,但我找不到解決方案。

索引.php:

include_once('Post.php');

if(isset($_GET['postId'])) {
    Post::likePost($_GET['postId'], $userId);
}

//Here sql to select postText, postId...
//Here echo the post

<form action="index.php?postId='.$postId.'" method="post">   
    <input type="submit" name="like" value="Like">
    <input type="submit" name="unlike" value="Unlike">
</form>


Post.php:

class Post {
    public static function likePost($postId, $likerId) {
        //select database and check if user already liked post. If yes: -1 like if no: +1 like
    }
}

有誰知道我是否可以使用 AJAX 發送Post::likePost($_GET['postId'], $userId); 所以我可以在不刷新like情況下點贊帖子?

這是您可以嘗試的方法。 代碼注釋很好

<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script 
  src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 
  type="text/javascript" charset="utf-8"></script>


<script>

$(document).ready(function(){
  $(".like, .unlike").click(function(){ 

var postId= 1;
//var post1 = $('#postId').val();
 var id_likeunlike = this.id;   // Getting Button id for like or unlike
var userId= 101;

var datasend = "postId="+ postId + "&id_likeunlike=" + id_likeunlike + "&userId=" + userId;

// display a loading image when sending ajax request
$('#loader').fadeIn(400).html('<br><span class="well"><img src="loader.gif" align="absmiddle">&nbsp;Please Wait, Your Data is being Submitted</span>');

        $.ajax({

            type:'POST',
            url:'post.php',
            data:datasend,
                        crossDomain: true,
            cache:false,
            success:function(msg){
$('#loader').hide();
            alert('success');   

                $('#listpost').fadeIn('slow').prepend(msg);

            }


        });


});

});




</script>
  </head>
    <body>
<div id="loader"> </div>
    <div id="listpost"> </div>


    <input type="submit" id="like" class="like" name="like" value="Like">
    <input type="submit" id="unlike" class="unlike"  name="unlike" value="Unlike">

</body>

郵政php

<?php

$postId = intval($_POST['postId']); 
$id_likeunlike = strip_tags($_POST['id_likeunlike']); 
$userId = strip_tags($_POST['userId']); 


if($id_likeunlike=='like'){
echo "like success";
}
elseif($id_likeunlike=='unlike'){
echo "unlike success";
}

else{
echo "Error occured";
}


?>

您可以簡單地在主頁上的JavaScript中調用ajax到另一個專用於 Like/Unlike 處理的 PHP 頁面

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM