我想要一个像 Facebook 一样的按钮编码。我试过了,但问题是没有显示通过 AJAX 从其他 PHP 文件返回的数据。这是我的代码。
SQL
CREATE TABLE `imagedata` (
`id` int(10) DEFAULT NULL,
`image` varchar(1000) DEFAULT NULL,
`upload_by` int(10) DEFAULT NULL
)
CREATE TABLE `likedata` (
`liked_by` int(10) DEFAULT NULL,
`image_id` int(10) DEFAULT NULL
)
CREATE TABLE `userdata` (
`id` int(2) NOT NULL,
`names` varchar(10) NOT NULL
)
数据库.php
$cn=mysql_connect("localhost","root","");
if(!$cn){
echo "Database problem occur.";
die();
}
$db=mysql_select_db("test",$cn);
if(!$db){
echo "Database not exist.";
die();
}
function getLike($tablename,$image_id){
$num=0;
$result=mysql_query("select liked_by from $tablename where image_id=$image_id");
$num=mysql_num_rows($result);
return $num;
}
function getCheck($tablename,$id,$image_id){
$n=0;
$result=mysql_query("select * from $tablename where liked_by=$id and image_id=$image_id");
$n=mysql_num_rows($result);
return $n;
}
AJAX.php
<?php
require_once("db.php");
session_start();
if(!isset($_SESSION["id"])){
echo "Please login";
die();
}
$id=$_SESSION["id"];
echo "LOGIN ID = ".$id."<p><br></p>";
$result=mysql_query("select * from imagedata");
while($row=mysql_fetch_assoc($result)){
$image_id=$row["id"];
$pic=$row["image"];
$upload_by=$row["upload_by"];
$no=getCheck("likedata",$id,$image_id);
$num=getLike("likedata",$image_id);
if($no>0){
echo "<p><img src='$pic' /></p>";
echo "<span id='no_likes'>$num</span> <a onclick='ajaxLike($id,$image_id)' id='status'>unlike</a>";
}
else{
echo "<p><img src='$pic' /></p>";
echo "<span id='no_likes'>$num</span> <a onclick='ajaxLike($id,$image_id)' id='status'>like</a>";
}
}
?>
AJAX.js
function ajaxLike(id,image_id){
var doc=new XMLHttpRequest();
var url="like.php";
var data="id="+id+"&image_id="+image_id;
doc.open("POST",url,true);
doc.setRequestHeader("Content-type","application/x-www-form-urlencoded");
doc.onreadystatechange=function(){
if(doc.readyState==4 && doc.status==200){
var info=doc.responseText;
var arr=info.split(" ");
document.getElementById("no_likes").innerHTML=arr[0];
document.getElementById("status").innerHTML=arr[1];
}
}
doc.send(data);
document.getElementById("status").innerHTML="processing.....";
}
喜欢.php
<?php
require_once("db.php");
if($_POST["id"]!="" && $_POST["image_id"]!="" && $_POST["status"]!=""){
$id=$_POST["id"];
$image_id=$_POST["image_id"];
$status=$_POST["status"];
$no=mysql_num_rows(mysql_query("select * from likedata where liked_by=$id and image_id=$image_id"));
if($no>0){
mysql_query("delete from likedata where liked_by=$id and image_id=$image_id");
$num=mysql_num_rows(mysql_query("select liked_by from likedata where image_id=$image_id"));
echo $num." "."like";
}
else{
mysql_query("insert into likedata values($id,$image_id)");
$num=mysql_num_rows(mysql_query("select liked_by from likedata where image_id=$image_id"));
echo $num." "."unlike";
}
}
?>
当我点击喜欢/不喜欢按钮后检查数据库时,它会显示我想要的结果。Bt 如果不按 F5 刷新页面,它不会显示在页面上。帮助..