[英]how to pass array of javascript objects to php?
我有一堆需要傳遞給服務器的值,而且似乎無法使JSON解碼等基本功能正常工作。 這里有些事,我會很感激有人看的
我有一個動態生成的表,該表具有可編輯的值,當用戶單擊“添加”按鈕時,該表會被捕獲,將其壓入數組,然后通過ajax調用發送到服務器。 這是從console.log(data)復制過來的示例數據。 線。
var data = params + "&Details="+JSON.stringify(Details);
console.log(data); // &Id[]=1566&aId[]=1567&Details=[["1566","First File","sdf.pdf","general","file","",""],["1567","2nd file","test.png","image","file","",""]]
$.ajax({
type: 'POST',
url: editUrl,
dataType: 'json',
data: data,
success: function() { console.log('success'); }
error: function() { console.log('error'); }
});
在服務器端,我得到了數據,但無法將其解析為可用格式
$ids = ($_POST['Id']); // this is a valid array
$details = ($_POST['Details']); // [[ 1566 , First File , , general , file , , ],[ 1567 , 2nd file , , image , file , , ]]
$details = json_decode($details); // getting JSON_ERROR_CTRL_CHAR error and null is returned
知道這里有什么問題嗎?
您需要正確編碼JSON:
var data = params + "&Details="+encodeURIComponent(JSON.stringify(Details));
但是,恕我直言,使data
成為對象而不是字符串會更好。
var data = {
Id: [ 1566, 1567],
Details: JSON.stringify(Details)
};
您將需要更改創建params
以便它也可以生成對象。 然后,您可以使用$.extend()
合並它們:
var data = $.extend({}, params, { Details: JSON.stringify(Details) });
您的ajax參數在成功函數后缺少comma
,並嘗試將服務器的成功函數回調定義為數據,然后將json_encode用於php服務器中的數組數據。
$.ajax({
type: 'POST',
url: editUrl,
dataType: 'json',
data: data,
success: function(data) { console.log(data); },
error: function() { console.log('error'); }
});
不確定如何構建params變量或為什么。 但是,如果只是通過ajax發送,則不必這樣做。 ajax的data參數將為您完成此操作。 給它一個帶有您要發送的名稱/值對的對象。
$.ajax({
type: 'POST',
url: editUrl,
dataType: 'json',
data: {
Id: [2566],
aId: [1567],
Details: Details,
Other: 'Hi',
AnotherId: 1234
}
success: function() { console.log('success'); }
error: function() { console.log('error'); }
});
在服務器上,查看所有$ _POST變量,以了解發送的內容和格式
<?php
echo '<pre>'
print_r($_POST);
?>
嘗試json_decode(stripslashes($details))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.