我需要帮助添加到数据库中。我想从按钮点击方法调用一个javascript scrt。Javascript脚本,我想调用一个php文件,其中包含一些添加到MySQL数据库的代码。
我真的尝试了20多个网站,但没有任何帮助。
如果AJAX会更好,你能帮我吗?
按钮代码:
<input type="button" value="favorites1" onClick="favfunct();">
Javascript代码
function favfunct() {
var target = document.createElement( "script" );
target.setAttribute( "src", "php/addtofavorites.php" );
document.getElementsByTagName( "body" )[0].appendChild( target );`
}
Php代码
<?php
echo "test successful"
$con = mysql_connect("localhost","root","student");
if ($_POST["get"] == 'runfunction')
echo "Works";
}
if ($_POST["action"] == 'favorites1'){
echo "Testing Was Successful"
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("tvid", $con);
$sql="INSERT INTO Persons (userid, davorites) VALUES
('1','$_POST[video0]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Your Video was Added To Your Favorites";
mysql_close($con)
}
?>
所以,这个"作品";就像敲螺丝一样。它会进入那里,但不是你真正想要的做事方式。
不要使用脚本标记来触发php页面。你的页面会触发,但它是完成任务的错误工具。你想使用AJAX。AJAX是专门为这个目的而设计的,而脚本标记是为了在页面上运行脚本。它将尝试获取addtofavorites.php
的内容,但它将期望JavaScript作为返回。您将无法使用$_POST
,因为您无法将数据发布到请求中。
相反,使用AJAX。如果你已经在使用JavaScript库,那么它将为你提供一个很好的AJAX包装器(我不知道有哪个库没有)。您可以查看API文档,为您提供关于如何使用AJAX功能的文档库(jQuery、Prototype.js、Mootools等)
作为一个例子,我将使用jQuery,因为它是最流行的查询之一。下面是一个使用jQuery到您的页面的请求(以及预期的变量)
// Call an AJAX function to the proper page
$.ajax("php/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.
}
});
另外,附带说明一下,PHP中的每一行都需要在末尾使用分号;
。第三行缺少一个左括号{
,但我不确定这是否只是复制粘贴的产物。
附录
我建议使用jQuery来监听事件。jQuery的事件API将允许您监听对象上的事件。所以,像这样的东西:
<input id="button_1" type="button" value="favorites1" />
和jQuery
$(document).ready(function () { // Make sure the elements are loaded on the page
// Listen for a click event on the button
$('#button_1').click(favfunct);
});
// Now define the function
function favfunct(e) {
// Stop the page from "following" the button (ie. submitting the form)
e.preventDefault();
e.stopPropagation();
// Insert AJAX call here...
}
我推荐jQuery,
这正是您所需要的:http://api.jquery.com/jQuery.get/
function add(title,text) {
$(function() {
$.get("add_to_db.php?title="+title+"&text="+text);
});
}
您可以使用更高级的方法http://api.jquery.com/jQuery.post/