jQuery 中的 Ajax 是这样工作的:
var myData=1;
$.ajax({
type:'POST',//type of ajax
url:'mypage.php',//where the request is going
data:myData,//the variable you want to send
beforeSend:function(xhr){//as a standard, I add this to validate stuff
if(someThingWrong===true)xhr.abort//aborts xhttpRequest
},
success:function(result){
//result is your result from the xhttpRequest.
}
});
这不会刷新您的页面,而是向指定的 url 发送“POST”。在您指定的页面上,您想做任何您想做的事情并说返回结果。在我的示例中,我将做一些简单的事情:
if($_POST['myData']===1)return True;
这是使用 jQuery 的 AJAX 请求的基础知识。
编辑!
启动 AJAX 脚本:
我只是猜测,因为我不知道您的 html 中的元素,也不知道您的脚本!所以你必须做出调整!
$('button.dislike').click(function(){
$.ajax({
type:'POST',
url:'disliked.php',
data:{dislike:$(this).attr('id')},
success:function(result){
$(this).prev('span').append(result);
}
});
});
PHP:
不要使用mysql,它现在已经被贬值并且被认为是不好的做法,我也不知道为什么在查询上使用sprintf? :S
$DBH=new mysqli('location','username','password','database');
$get=$DBH->prepare("SELECT dislike FROM random WHERE ids=?");
$get->bind_param('i',$_POST['dislike']);
$get->execute();
$get->bind_result($count);
$get->close();
$update=$DBH->prepare('UPDATE random SET dislike=? WHERE ids=?');
$update->bind_param('ii',++$count,$_POST['dislike']);//if you get an error here, reverse the operator to $count++.
$update->execute();
$update->close();
return String $count++;
只有在您的 HTML 中有一系列 ID 与数据库中的按钮匹配的按钮时,这才有效。所以
$get=$DBH->prepare('SELECT ids FROM random');
$get->execute();
$get->bind_result($ids);
while($get->fetch()){
echo"<button class='dislike' id='".$ids."'>Dislike this?</button>";
}
希望您大致了解我如何管理您的不喜欢按钮系统 XD 哈哈