簡體   English   中英

AJAX不會通過POST將數據傳遞到其預期的URL

[英]AJAX is not passing data via POST to its intended URL

我想通過AJAX傳遞數組,但是我沒有得到任何反饋。 我試圖做一個var_dump($_POST); 在PHP方面( next.php ),但沒有任何顯示。 我猜我的代碼有問題。

function sendToServer(data) {
    $.ajax({
        type: "POST",
        data: { arr: JSON.stringify(data) },
        url: "next.php",
        success: function() {}
    });
}

next.php

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

?>

我的代碼的完整摘要:

 <!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 + '\\')">Remove</span>' + '</div>'; $("#" + id).append(str); } function removeDiv(id) { $("#" + 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); }); 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() { } }); } </script> </body> </html> 

問題是當您嘗試回顯該項目時。 由於$ item是一個對象(stdClass),並且echo命令需要一個字符串,因此echo命令失敗,並顯示“ stdClass無法轉換為字符串”。 您可以更改為:

回聲print_r($ item,true);

要么:

后續代碼var_dump($項目);

暫無
暫無

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

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