简体   繁体   English

如何使用AJAX将对象数据数组插入数据库

[英]How do I insert an object data array into a database with AJAX

I want to insert data from an array into a database table in the submit() function where the sql syntax is at. 我想将数组中的数据插入到sql语法所在的submit()函数中的数据库表中。 I want to insert the data then redirect to another page after successful. 我想插入数据,然后在成功后重定向到另一个页面。 I don't know how to do this with ajax. 我不知道如何用ajax做到这一点。

I tried to make ajax syntax but I don't know if i'm passing the data correctly for obj.name and obj.books corresponding to their own values in the array. 我试图制作ajax语法,但我不知道我是否正确传递了数据,因为obj.name和obj.books对应于数组中自己的值。

example: [{"name":"book1","books":["thisBook1.1","thisBook1.2"]},{"name":"book2","books":["thisBook2.1","thisBook2.2","thisBook2.3"]}] 例如:[{“name”:“book1”,“books”:[“thisBook1.1”,“thisBook1.2”]},{“name”:“book2”,“books”:[“thisBook2.1” “thisBook2.2”, “thisBook2.3”]}]

function submit(){
    var arr = [];
    for(i = 1; i <= authors; i++){
        var obj = {};
        obj.name = $("#author" + i).val();
        obj.books = [];
        $(".auth" + i).each(function(){
            var data = $(this).val();
            obj.books.push(data);
        });
        //sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
        //mysqli_query(sql);
        arr.push(obj);
    }

    $("#result").html(JSON.stringify(arr));
}
/////////////////////////////////
//I tried this:
$.ajax({
   type: "POST",
   data: {arr: arr},
   url: "next.php",
   success: function(){

   }
});
/////////////////////////////////

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <style type="text/css"> <!-- #main { max-width: 800px; margin: 0 auto; } --> </style> </head> <body> <div id="main"> <h1>Add or Remove text boxes with jQuery</h1> <div class="my-form"> <form action"next.php" method="post"> <button onclick="addAuthor()">Add Author</button> <br> <br> <div id="addAuth"></div> <br> <br> <button onclick="submit()">Submit</button> </form> </div> <div id="result"></div> </div> <script type="text/javascript"> var authors = 0; function addAuthor() { authors++; var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\\'auth' + authors + '\\')" >Add Book</button>' + '</div>'; $("#addAuth").append(str); } var count = 0; function addMore(id) { count++; var str = '<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\\'bookDiv' + count + '\\')" style="font-size: 20px; background-color: red; cursor:pointer; margin-left:1%;">Remove</span>' + '</div>'; $("#" + id).append(str); } function removeDiv(id) { //var val = confirm("Are you sure ..?"); //if(val){ $("#" + id).slideUp(function() { $("#" + id).remove(); }); //} } function submit() { var arr = []; for (i = 1; i <= authors; i++) { var obj = {}; obj.name = $("#author" + i).val(); obj.books = []; $(".auth" + i).each(function() { var data = $(this).val(); obj.books.push(data); }); // sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')"); // mysqli_query(sql); arr.push(obj); } $("#result").html(JSON.stringify(arr)); } </script> </body> </html> 

Send your array to server ,stringify array before sending it to server so in server you can decode json and recover your array, and then insert received data to database 将数组发送到服务器,stringify数组然后发送到服务器,这样在服务器中你可以解码json并恢复你的数组,然后将接收的数据插入数据库
JS JS

function submit(){
    var arr = [];
    for(i = 1; i <= authors; i++){
        var obj = {};
        obj.name = $("#author" + i).val();
        obj.books = [];
        $(".auth" + i).each(function(){
            var data = $(this).val();
            obj.books.push(data);
        });

        //sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
        //mysqli_query(sql);
        arr.push(obj);
    }
    sendToServer(arr)
    $("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
   $.ajax({
      type: "POST",
      data: {arr: JSON.stringify(data)},
      url: "next.php",
      success: function(){

      }
   });
}

PHP (next.php) PHP(next.php)

$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
   echo $d;
   // insert to db
}

Please Keep the following in mind 请记住以下几点

Javascript/JQuery is client side and hence cannot access the database which is on the server. Javascript / JQuery是客户端,因此无法访问服务器上的数据库。

You can Send data via AJAX to next.php and then use this data to insert into your database. 您可以通过AJAX将数据发送到next.php,然后使用此数据插入数据库。

To improve debugging, use the following code to ensure the correct data is being delivered in next.php 要改进调试,请使用以下代码以确保在next.php中传递正确的数据

   var_dump($_POST);

Your SQL statements must be executed in next.php using the data passed by $_POST (since your "type" of AJAX request is post). 您的SQL语句必须使用$ _POST传递的数据在next.php中执行(因为您的“类型”的AJAX请求已发布)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM