使用ajax和php多次将值插入数据库

时间:2014-10-13 16:00:56

标签: javascript php jquery mysql ajax

使用ajax和php将值插入到数据库中,使用此代码只插入一个值,我不知道为什么请帮助我。

PHP编码

$content=$_POST['content'];
$text=$_POST['text'];
mysql_query("insert into ajax(ajax,text) values ('$content','$text')");

ajax编码

$(function() {
    $(".comment_button").click(function() {

        var test = $("#content").val();
        var text = $("#text").val();

        var dataString = 'content='+ test;
        var datastring = 'text='+ text;

        if(test=='') {
            alert("Please Enter Some Text");        
        } else {
            $("#flash").show();
            $("#flash").html('<img src="loading.gif" align="absmiddle">&nbsp;<span class="loading">Wait..!</span>');            
            $.ajax({
                type: "POST",
                url: "demo_insert.php",
                data: dataString + datastring,
                cache: false,
                success: function(html) {
                    //document.getElementById('content').value='';
                    $("#flash").hide();
                    alert("Values Inserted Successfully");
                    //document.write("values inserted Successfully..."); // to show message as string           
                }
            });
        }

        return false;
    });
});

1 个答案:

答案 0 :(得分:1)

var dataString = 'content='+ test;
var datastring = 'text='+ text;

在上面的代码中,您重新声明了覆盖第一个变量数据的变量

最好的方法是

$.ajax({
  type: "POST",
  url: "demo_insert.php",
  data: {content:test, text: text},
  cache: false,
  success: function(html){
 //document.getElementById('content').value='';
 $("#flash").hide();
 alert("Values Inserted Successfully");
 //document.write("values inserted Successfully..."); // to show message as string
  }
});