簡體   English   中英

如何使用AJAX將對象數據數組插入數據庫

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

我想將數組中的數據插入到sql語法所在的submit()函數中的數據庫表中。 我想插入數據,然后在成功后重定向到另一個頁面。 我不知道如何用ajax做到這一點。

我試圖制作ajax語法,但我不知道我是否正確傳遞了數據,因為obj.name和obj.books對應於數組中自己的值。

例如:[{“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> 

將數組發送到服務器,stringify數組然后發送到服務器,這樣在服務器中你可以解碼json並恢復你的數組,然后將接收的數據插入數據庫
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)

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

請記住以下幾點

Javascript / JQuery是客戶端,因此無法訪問服務器上的數據庫。

您可以通過AJAX將數據發送到next.php,然后使用此數據插入數據庫。

要改進調試,請使用以下代碼以確保在next.php中傳遞正確的數據

   var_dump($_POST);

您的SQL語句必須使用$ _POST傳遞的數據在next.php中執行(因為您的“類型”的AJAX請求已發布)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM