[英]Send multidimensional form array via .ajax post to PHP prepared statement
[英]How to get multidimensional array from FORM via post, ajax, php, jquery?
請幫助我重新編碼。 我需要ajax這樣的數組:car1 ['car的顏色'] ['car的故事']。 但是我只能得到:car1 ['關於汽車的故事']。 我讀了很多技巧,但沒有成功。 我是php的初學者。 非常感謝您的具體回答:)
// HTML smaller version
<form class= "ajax2" action="formInsertCar.php" method="POST">
<input type="submit" value="Save All">
<div>
<select name="car1[]" size="1">
<?php $opt = new CarOptions;?>
</select>
<textarea name="car1[]"></textarea>
</div>
<div>
<select name="car2[]" size="1">
<?php $opt = new CarOptions;?>
</select>
<textarea name="car2[]"></textarea>
</div>
</form>
// JavaScript, ajax for FORM
$('form.ajax2').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
// here I want to result like: car1['color of car']['story about car'];
// but I can get only: car1['story about car']
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$('.success').html(response);
}
});
return false;
});
嘗試以下腳本..........使用JQuery FormData類
$('form.ajax2').on('submit', function(e) {
e.preventDefault();
url = that.attr('action'),
type = that.attr('method');
$.ajax({
url: url,
type: type,
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(response) {
$('.success').html(response);
}
});
return false;
});
我很確定這樣做會得到不需要的格式。 我會這樣做:
<div>
<select name="car[1][color]" size="1">
<?php $opt = new CarOptions;?>
</select>
<textarea name="car[1][history]"></textarea>
</div>
<div>
<select name="car[2][color]" size="1">
<?php $opt = new CarOptions;?>
</select>
<textarea name="car[2][history]"></textarea>
</div>
我還將更改您的一些JavaScript表單提交偵聽器:
$('form.ajax2').on('submit', function(e) {
e.preventDefault(); //'return false' is deprecated according to jQuery documentation, use this instead.
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = that.serialize(); //This will capture all form input values, no need to reinvent the wheel
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$('.success').html(response);
}
});
});
在服務器端(PHP):
print_r($_POST)
/**
Will print the following data:
array() {
car => array () {
1 => array() {
color => colorValue,
history => historyValue
},
2 => array() {
color => colorValue,
history => historyValue
}
}
}
*/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.