我的JavaScript有什么问题?在没有刷新页面的情况下,它正在某处添加记录。
我现在在一些有经验的用户的帮助下完全删除了。但现在添加记录到数据库还没有工作
我想现在动态添加记录而不刷新..删除功能正常并且正在数据库中反映出来。
我将包含4个文件和我的数据库:
index.php
add.php
用于添加记录delete.php
用于删除记录index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
</head>
<body>
<?php
include("dbconfig.php");
$sql = "SELECT * FROM games";
$result = mysql_query($sql);
while ($record = mysql_fetch_array($result)){
echo "<p class=\"p" .$record['ID']. "\"></br> Game ID: " .$record['ID']. "</br> Game Name: " .$record['Name'].
"<br /> Game Type: ".$record['Type']. "<br /> Rating: ".$record['Rating']."<br /> Year Released: ".$record['Release Year']."<br /> <br />" ?>
<a href="#" id="<?php echo $record["ID"]; ?>" class="deletebutton"><img src="trash.png" alt="delete"/> </a></p>
<?php
}
?>
<form name="add" id ="add" action="" method="post">
<input class ="gameID" type="hidden" id="ID" name="ID" value = " ' .$record['ID'] . ' " />
<b>Game Name: </b> <input type="text" id="name" name="name" size=70>
<b>Game Type:</b> <input type="text" id="type" name="type" size=40>
<b>Rating: </b> <input type="number" id="score" name="score" min="1.0" max="10.0" step ="0.1"/>
<b>Year Released: </b> <input type="number" min="1900" max="2011" id="Yreleased" name="Yreleased" value="1985" size=4>
<p><input type="submit" name="Submit" id = "Submit" value="Add Game" class = "add games"></p>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("#add").submit(function(){
var name = this['name'].value;
var type = this['type'].value;
var rating = this['score'].value;
var release = this['Yreleased'].value;
var dataString = 'name='+ name + '&type=' + type + '&rating=' + rating + '&release=' + release;
if (name == '' || type == '' || rating == '' || release == ''){
alert("please enter some valid data for your game entry");
}else
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function(){
window.location.reload(true);
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
}
)});
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("a.deletebutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var parent = $(this).parent();
if(confirm("Sure you want to delete this game? !..There is no Undo")){
$.ajax({
type: "get",
url: "delete.php?" + info,
context: document.body,
success: function(){
$('.p'+del_id).html('deleted');
$('.success').fadeIn(200).show();
}
});
}
return false;
});
});
</script>
</body>
</html>
add.php
<?php
require('dbconfig.php'); //we cannot continue without this file, thats why using require instead of include
if(isset($_POST['name']))
{
$name=addslashes($_POST['name']);
$type=addslashes(($_POST['type']));
$rating=addslashes($_POST['rating']);
$release=addslashes($_POST['release']);
$sql = 'INSERT INTO `games` (`Name`,`Type`,`Rating`,`Release Year`) VALUES ("'.$name.'", "'.$type.'", "'.$rating.'", "'.$release.'")';
mysql_query( $sql);
if(!mysql_errno())
echo " your game has been added to the list of games. ";
}
?>
delete.php
<?php
require('dbconfig.php'); //we cannot continue without this file, thats why using require instead of include
if(isset($_GET['id']))
{
$id=(int)$_GET['id'];
$sql = 'DELETE FROM `games` WHERE `ID`="'.$id.'" LIMIT 1';
mysql_query( $sql);
echo 'deleted';
}
?>
<?php
$user_name = "root";
$password = "";
$database = "gamebook";
$server = "localhost";
$bd = mysql_connect($server, $user_name, $password) or die ('I cannot connect to the database because:' . mysql_error());
mysql_select_db($database);
?>
如果需要,这里也是我的数据库的架构:
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `gamebook`
--
CREATE DATABASE `gamebook` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `gamebook`;
-- --------------------------------------------------------
--
-- Table structure for table `games`
--
CREATE TABLE IF NOT EXISTS `games` (
`ID` int(4) NOT NULL AUTO_INCREMENT,
`Name` varchar(70) COLLATE utf8_unicode_ci NOT NULL,
`Type` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`Rating` float NOT NULL,
`Release Year` int(4) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=7 ;
--
-- Dumping data for table `games`
--
INSERT INTO `games` (`ID`, `Name`, `Type`, `Rating`, `Release Year`) VALUES
(1, 'Battlefield 3', 'First Person Shooter', 8.5, 2011),
(2, 'Fifa 12', 'Sports', 9.2, 2004),
(3, 'Red Alert 3', 'Strategy ', 8.8, 2007),
(4, 'Fight Night Round 4', 'Fighting', 9, 2010),
(5, '', '', 0, 0),
(6, '', '', 0, 0);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
我的javascript有什么问题,找出最好的方法是什么?
你们为像我这样的初学者推荐一个好的文本编辑器吗?
答案 0 :(得分:2)
我注意到了一些事情。
首先,您的JavaScript语法已关闭。在您的第一个文件(index.php
)中,您有以下行:
$("#add").load("add.php") {
这不是.load()
方法的正确语法。基本上,你有这个:
$("#add").load("add.php") {
// ... stuff to happen after add.php loads
}
应该拥有的是:
$("#add").load("add.php", function() {
// .. stuff to happen after add.php loads
});
请记住,您需要以回调的形式添加此额外功能,否则它无法正常工作。
在我提到的第一个代码块中,看起来您正在尝试加载add.php
,然后在加载后发出一些JavaScript命令。但是查看add.php
文件的来源,您不希望这样做。您的add.php
文件包含要处理的记录到数据库的服务器端代码...您不直接加载它,只需向其提交POST请求。
您没有正确地将数据发送到服务器。使用add例程,您首先要创建一个数据字符串:
var dataString = 'ID=' + id 'name='+ name + '&username=' + type + '&password=' + rating + '&gender=' + release;
然后你通过AJAX在数据包中发送它:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
这里的问题是双重的。首先,您没有正确编码数据。 'ID=' + id 'name='
缺少+
个字符并会中断。但即使修复了这个问题,你也会不正确地连接数据。您的dataString
变量最终会显示为:
ID=1name=Bob&username=my_user&password=password&gender=male
您是否看到错过了&
符号?这是一个容易犯的错误,因此请发送数据对象。你不太可能错过角色:
$.ajax({
type: "POST",
url: "add.php",
data: {
},
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
接下来,您将数据传递到服务器,但检查不同的值。您添加数据的JavaScript看起来像是要发送:
但是您的add.php
正在检查:
使用删除例程,您将在GET中检查“ID”的值。这意味着该值需要作为附加到URL的查询参数传递。例如:delete.php?ID=5
删除ID为5的游戏。
你在PHP中检查这个很好,但你实际上并没有在你的AJAX请求中发送数据。您的代码 应该更像这样:
$("a.deletebutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var parent = $(this).parent();
if(confirm("Sure you want to delete this game? !")){
$.ajax({
type: "get",
url: "delete.php?" + info,
context: document.body,
success: function(){
$('.p'+del_id).html('deleted');
}
});
}
return false;
});
看url: "delete.php"
成为url: "delete.php?" + info
?这会将您的ID附加到网址,并在PHP中提供$_GET['id']
。
答案 1 :(得分:0)
从第一眼看,我可以告诉id不作为参数传递给delete.php脚本。尝试将data: info
添加到ajax调用中。这可能是让它发挥作用的第一步。
我看到的另一个问题是$(this).attr("id")
不会给你删除游戏的ID,而是按钮元素的id("Submit"
)。相反,您应该使用$("#ID").val()
从隐藏字段中获取值。