【问题标题】:Ajax Listen Event on a Button Click then Runs a Php file按钮上的 Ajax 侦听事件单击然后运行 ​​PHP 文件
【发布时间】:2012-03-16 12:56:24
【问题描述】:

如果单击按钮,我需要 AJAX 来监听。然后,如果是我需要它来运行 PHP 脚本。我遇到了 AJAX 无法正确收听按钮单击的问题,因此它从不运行脚本。
您可能会在我的代码中看到任何错误?
关于我应该如何做到这一点的任何建议?

按钮:

<input id="button_1" type="button" value="favorites1" onclick="favfunct();" />

调用它的 AJAX 是:(ajaxlisten.js)

<script type="text/javascript">

    $(document).ready(function () { // Make sure the elements are loaded on the page
        // Listen for a click event on the button
        $('#button_1').click(favfunct);
    });

    function favfunct(e) {
        // Stop the page from "following" the button (ie. submitting the form)
        e.preventDefault();
        e.stopPropagation();

        // Call an AJAX function to the proper page
        $.ajax("js/addtofavorites.php", {
            // Pass our data to the server
            data: { "get" : "runfunction", "action" : "favorites1" },
            // Pass using the appropriate method
            method: "POST",
            // When the request is completed and successful, run this code.
            success: function (response) {
            // Successfully added to favorites. JS code goes here for this condition.
                alert ("successfully loaded")
            }          
        });
    }
</script>

PHP 文件 (addtofavorites.php)

<?php
$con = mysql_connect("localhost","root","student");

if ($_POST["action"] = 'favorites1')
{ 
    if (!$con);
    {
        die('Could not connect: ' . mysql_error());
    }                   
    mysql_select_db("tvid", $con);

    $sql="INSERT INTO tv (userid, favorites) VALUES (345,77);"
    if (!mysql_query($sql,$con));
    {
        die('Error: ' . mysql_error());
    }
    echo "Your Video was Added To Your Favorites";
    mysql_close($con);
}
?>

【问题讨论】:

  • $.ajax 没有 method 属性。 type 决定了它是POST 还是GET。无论如何,它没有“正确听”是什么意思?您是否遇到任何类型的错误或没有任何反应?
  • 它不运行 addtofavorites.php 脚本。该按钮什么也不做,即使我在单击时引用它来执行某些操作。

标签: php jquery html ajax button


【解决方案1】:

尝试重写click函数:

$(document).ready(function () { 
   $('#button_1').click(function(e){
        e.preventDefault();
        e.stopPropagation();
        favfunct();
   });
});

然后favfunct

function favfunct() {
// AJAX Call Below
// rest of your code

这应该让您的favfunct 运行。之后,您可以根据需要进一步调试代码。

您也可以取消按钮上的onclick

<input id="button_1" type="button" value="favorites1" />

小提琴演示:http://jsfiddle.net/sbybd/

ajax 调用示例:

$.ajax({
     type: "POST",
     url: "js/addtofavorites.php",
     data: { "get" : "runfunction", "action" : "favorites1" },
     success: function (response) {
         alert ("successfully loaded");
     }    
 });

【讨论】:

  • 知道如何让 AJAX 成功调用 Php 文件以添加到数据库吗?
  • @JulianNeill 您需要正确编写它。有关更多信息,请参阅jquery docs,我更新了我的答案以包含一个示例。
  • 谢谢你会更多地研究它
猜你喜欢
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 2013-03-14
  • 2015-07-31
  • 1970-01-01
  • 2023-04-03
  • 2013-11-08
相关资源
最近更新 更多