javascript post onclick from php



我有以下脚本,它根据数据库结果显示图像。当用户单击图像时,它将更改为新图像。green_star表示数据库中存在$user_id$thedb_idgrey_star表示它们不存在。我正在寻找一种在单击星星时插入数据库或从中删除的方法。在PHP中,我知道我会这样做

INCLUDE 'addTo_watchlist.php?user_id=$user_id&thetvdb_id=$thetvdb_id';

但是JavaScript不接受这种格式的帖子数据。是否有可能做我正在寻找的事情,如果是这样,最好的路线是什么?

<script type="text/javascript">
   function changeIt(id) 
{
    var theImg = document.getElementById(id),
             x = theImg.src.split("/"),
             t = x.length-1,
             y = x[t];
    if(y == 'grey_star.gif')
    {
        theImg.src='./images/green_star.gif'
    }
    if(y == 'green_star.gif')
    {
        theImg.src='./images/grey_star.gif'
    }
}
</script>
<a onclick="changeIt('<?php echo $img_id; ?>')"><img src='<?php echo $image; ?>' name='<?php echo $img_id; ?>' id='<?php echo $img_id; ?>'  border='0' width='50%' /></a>

我认为你的问题在几个方面令人困惑;尤其是因为你似乎将GET数据称为POST数据(这是提交表单数据的两种不同方式)。但是,我相信您的意思是询问如何通过JavaScript添加或删除数据库条目。

答案是AJAX(异步JavaScript和XML)。

看这里:

http://www.ibm.com/developerworks/web/library/wa-aj-ajaxhistory/index.html?ca=dathttp://www.w3schools.com/ajax/ajax_intro.asp

在这种情况下,您只需发出一个简单的 xmlhttprequest 来触发服务器端脚本。因此,例如,用于将电影添加到监视列表的 JavaScript 如下所示:

var xmlhttp;
if (window.XMLHttpRequest) {
  xmlhttp=new XMLHttpRequest();
} else {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Define the url and the GET data (don't forget to pass the userID and thetvdb_id variables from PHP to javascript)
xmlhttp.open("GET", "Path/addTo_watchlist.php?user_id="+userID+"&thetvdb_id="+thetvdb_id, true);
// Define what happens when the request's readystate changes
xmlhttp.onreadystatechange = function() {
  // Define what happens if the script was successful (similar conditions can be added for other readystates and status codes)
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
     // Change was successful
     theImg.src='../images/green_star.gif'
  }
}
// Send the request
xmlhttp.send(); 

最新更新