[英]call function when onclick <a> , then increase count by one, update the change to database
div的內容由按“ cts”(計數)排序的數據庫生成。 當我單擊div時,我希望“ cts”數字加1,然后將更改更新到數據庫。 結果,內容將相應更改。 AJAX:
function addcount()
{
console.log('step1');
var id=this.rowid;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
console.log('step2');
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
console.log('step3');
document.getElementById("cts").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","addcount.php?q="+id,true);
xmlhttp.send();
}
PHP代碼:
<?php
require_once "db.php";
session_start();
$id=intval($_GET['id'])
$sql="UPDATE words SET cts=cts+1 WHERE id='$id'";
if (!mysqli_query($con,$sql)){
die('Error: ' . mysqli_error($con));
}
?>
-------這根本不起作用-------提前謝謝您。
?q="+id
和$_GET['id']
。
整個查詢字符串參數都需要使用相同的名稱。
將?q="+id
更改為?id="+id
或將$_GET['id']
更改$_GET['q']
。
您沒有確切說明問題所在,但是有一個問題是您要在調用open()
之前設置onreadystatechange
。 open
重置XMLHttpRequest
對象,因此即使服務器端應用程序運行正常,您的回調也不會執行。
將順序更改為:
xmlhttp.open("GET","addcount.php?q="id,true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
console.log('step3');
document.getElementById("cts").innerHTML=xmlhttp.responseText;
}
}
我遇到的問題就像Quentin所說:保持id和p相同。 所以我將?q="+id to ?id="+id
更改?q="+id to ?id="+id
我遇到的另一個問題是$(this).rowid不指向我想要的確切值。 因此,我使用參數來解決此問題。
現在運作良好。 謝謝大家的幫助。 HTML
onclick="addcount('.htmlentities($row['id']).');return false;"
AJAX:
function addcount(id)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","addcount.php?id="+id,true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log(xmlhttp);
document.getElementById("cts").innerHTML=xmlhttp.responseText;
}
else{
console.log(xmlhttp.readystatus);
console.log(xmlhttp.status);
}
}
xmlhttp.send();
}
PHP:
<?php
header("Content-type: text/html; charset=utf-8");
require_once "db.php";
session_start();
$id=intval($_GET['id']);
$sql="UPDATE words SET cts=cts+1 WHERE id='$id'";
if (!mysqli_query($con,$sql)){
die('Error: ' . mysqli_error($con));
}
?>
謝謝:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.