【问题标题】:javascript post onclick from phpjavascript从php发布onclick
【发布时间】:2014-01-04 20:59:47
【问题描述】:

我有以下脚本,它根据数据库结果显示图像。当用户单击图像时,它会更改为新图像。 green_star 表示$user_id$thedb_id 存在于数据库中,grey_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>

【问题讨论】:

    标签: javascript php post


    【解决方案1】:

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

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

    看这里:

    http://www.ibm.com/developerworks/web/library/wa-aj-ajaxhistory/index.html?ca=dat http://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(); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 2017-06-16
      • 1970-01-01
      相关资源
      最近更新 更多