[英]How to post an array of objects in JSON with Ajax Post to PHP?
我可以使用Ajax Post成功地將數組發布到PHP,但是我想擴展此功能以發布對象數組而不是值數組..im努力尋找方法的清晰示例。
這是我從jQuery / Javascript客戶端腳本中發布值數組的方式:
var placesfortrip = {};
placesfortrip["place"+counter] = inputVal;
//note counter is an int that gets incremented for each value
//inputVal is a string with the new value to be added
var inputVal = jQuery("#edit-location").val();
jQuery.ajax({
url: "/createtrips/updateitin",
type: 'POST',
data: placesfortrip,
dataType: 'json'
});
然后在PHP端讀取如下數據:
$citynames = array();
foreach ($_POST as $key=>$value) {
$citynames[$key]= $value;
}
如何修改以上內容以發布對象數組而不是值? 我對於如何從PHP端讀取對象數組特別困惑。
您可以嘗試使用此代碼將數據發送到php文件
var status = document.getElementsByName("status")[0];
var jsonObj = []; //declare array
for (var i = 0; i < status.options.length; i++) {
jsonObj.push({id: status.options[i].text, optionValue: status.options[i].value});
}
然后替換這行
data: placesfortrip,
與
data: jsonObj,
對於其他幫助,您也可以幫助這一
大多數流行的JavaScript框架都包含JSON實用程序功能。 例如,jQuery具有直接調用url並將JSON結果作為對象加載的函數: http : //docs.jquery.com/Getjson
但是,您可以從json網站獲取開源JSON解析器和字符串化器:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
然后,只需添加代碼並在數組上使用JSON.stringify()方法即可。
您也可以忘記json並按原樣發布數組。 例如JavaScript:
var slideShowImages = new Array();
var image = {};
image['id'] = 1;
image['title'] = "Title 1";
slideShowImages[0] = image;
等在javascript中填寫整個數組。 然后,Ajax調用為:
$.ajax({
type : 'POST',
url: BASE_REQUEST_URL + 'apiModule/performAddEditSlideShow',
cache: false,
data: {
images: slideShowImages
}
});
然后在PHP中,只需遍歷它:
$images = $_POST['images'];
foreach($images as $image) {
$title = $image['title'];
}
您應該能夠將對象發布到服務器,並使用json_decode($ _ POST ['some_key“])將該對象用作服務器上的數組/對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.