我希望能够看到AJAX传递的数据是否是函数sendToServer
中的正确数据。
当用户提交他/她想要的数据时,提交功能会将其发送到next.php
。我想看看next.php
正在接收什么,我该怎么做?应该收到与此相同的内容:
$("#result").html(JSON.stringify(arr));
这样我就可以将数据插入到MySQL数据库中。
next.php
:
<?php
$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>
&#13;
答案 0 :(得分:0)
您的js正在发送帖子请求,因此您应该收到发送的数据,就像您收到正常的html表单帖子一样。
尝试var_dump($_POST);
查看您的数据的索引名称,然后您可以使用这些索引名称来操作您想要的数据。