【发布时间】: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