2012-07-20 138 views
-3

到mysql我想用克隆的div包含表单使用此代码插入记录使用jquery

$(document).ready(function() { 

    $("#button").click(function() { 
     $("<div class='newclone' id='xxx'><article><form method='post' id='aj'><input type='checkbox'><label>Firstname</label><input type='text' value='' name='firstname'><label>Secondname</label><input type='text' value='' name='secondname'><label>City</label><input type='text' value='' name='city'><input type='hidden' value='4'></article><input type='submit' value='insert' class='one'><button class='two'>Delete</button><button class='three'>Cancel</button></form></div>").appendTo('.clone-container'); 
    }); 

    $('.one').click(function() { 
     $.ajax({ 
      type: "POST", 
      url: "insert.php", 
      data: $("#aj").serialize(), 
      success: function() { 
       alert('Inserted!'); 
      } 
     }); 
    }); 
}); 

这是php文件

$con = mysql_connect("localhost","root",""); 
if (!$con) 
    { 
    die('Could not connect: ' . mysql_error()); 
    } 
mysql_select_db("clone", $con); 

$firstname=$_POST['firstname']; 
$secondname=$_POST['secondname']; 
$city=$_POST['city']; 
mysql_query("INSERT INTO clone(firstname,secondname,city) VALUES ('$firstname','$secondname','$city')"); 

插入一条记录到数据库编辑

问题是,似乎没有发布

+0

什么是错误? – 2012-07-20 14:46:58

+2

http://bobby-tables.com/这是主要问题;) – haynar 2012-07-20 14:47:14

+3

StackOverflow不是“这是我的代码,修复它”。你的代码在做什么?你得到什么错误?你有没有尝试过自己调试? – 2012-07-20 14:48:09

回答

3

分别测试每个部分。 Ajax请求是否发送正确的数据? PHP脚本是否获得了数据? (尝试echo <pre>;print_r($_POST);exit;。)您的INSERT查询是否正确配制?它成功了吗?

你还不知道你的问题到底是什么。首先找出问题所在。那么可能很容易找出如何解决它。

+1

另外,作为一个单独的问题,您应该了解数据库输入卫生。这一点很重要。 – 2012-07-20 14:52:03

+0

Zsanks贾森zes kind words。我有$('。'')。live(“click”,function()注释掉,所以我恐慌了一下,但现在正在工作。 – Gandalf 2012-07-20 15:12:19

1

只有在点击了$("#button")之后,才会将$('.one')添加到DOM。所以,当$('.one').click(运行时,$('.one')尚不存在,所以事件没有绑定。

您需要使用委托(或“实时”)事件。

$(document).on('click', '.one', function(){ 
    // Click handler here 
});