1
我正在編程一個網頁,我真的試圖發送一個JSON對象數組到我的PHP後端腳本。如何發送JSON數組與jQuery
這(使用jQuery)我的javascript代碼:
var toSend = new Array();
$("input[type=checkbox]").each(
function (indice, item)
{
var dom = $(item);
var domJSON = {
id: dom.attr("value"),
checked: (dom.attr("checked") == "checked" ? true : false)
};
//put object as JSON in array:
toSend.push($.toJSON(domJSON));
}
);
$.ajax({
type:"POST",
url: "salvar_escala.php",
data: {checkbox: toSend},
success: function(response) {
$("#div_salvar").html(response);
},
error: function() {
alert("Erro");
}
}
);
而在PHP我有這樣的:
//Grab the array
$arrayFromAjax = $_POST['checkbox'];
foreach($arrayFromAjax as $aux) {
$temp = json_decode($aux, true);
$id = $temp['id'];
$value = $temp['checked'];
//This line doesn't print anything for $id and $value
echo "Id: $id | Value: $value<br />";
//This line prints an crazy string, but with right values
echo "CHEKBOX[] => $b<br />";
}
在這段代碼中,我在我的解碼對象JSON,然後把在一個數組中併發送。我也試過,但在陣列(無JSON)對象,然後將數組轉換成JSON,並把他們像:
$.ajax({
type:"POST",
url: "salvar_escala.php",
dataType: "json",
data: {checkbox: $.toJSON(toSend)},
success: function(response) {
$("#div_salvar").html(response);
},
error: function() {
alert("Erro");
}
}
);
但在這種情況下,更糟糕的是,誤差函數被調用。
謝謝你!我對json_encode/decode有點困惑! – IPValverde