如何在下面转换此Android代码
for (int i = 0; i < items.size(); i++) {
mParams.put("items[" + i + "][id]", items.get(i).getType().getId());
mParams.put("items["+i+"][note]", items.get(i).getNote());
}
迅速为alamofire。
以下是我的代码,但它不起作用:
for var i = 0; i < self.survey.items.count; i++ {
parameters["items[\(self.survey.items[i].type?.id)]"] = [
"[id]": self.survey.items[i].id,
"[note]": self.survey.items[i].note
]
print(self.survey.items[i].id)
}
-
parameters
看起来像:
parameter: [
"items[0][id]": 3,
"items[1][note]": Pen,
"lat": 3.070235299720939,
"status_id": 1,
"items[3][id]": 3,
"name": Bih,
"lng": 101.6110375110495,
"items[2][id]": 4,
"items[0][note]": Keychain,
"items[3][note]": Keychain,
"is_avocated": 1,
"items[2][note]": Pen,
"items[1][id]": 4
]
我设法只用
添加1parameters["items"] = [[
"id": 4,
"note": "Pen"
]]
但是一旦我做到了
parameters["items[0]"] = [[
"id": 4,
"note": "Pen"
]]
它没有添加:(再次没有错误
最新编辑:服务器端(Laravel)期待
$items = Input::get('items', []);
foreach ($items as $key => $item) {
//$survey->items()->attach($item['id'], ['note' => $item['note']]);
$sItem = new SurveyItem;
$sItem->survey_id = $survey->id;
$sItem->item_id = $item['id'];
$sItem->note = $item['note'];
$sItem->created_by = Auth::user()->id;
$sItem->save();
}
答案 0 :(得分:1)
与您的Android代码相当的Swift将是:
var parameters = [String:String]()
for var i = 0; i < survey.items.count; i++ {
parameters["items[\(i)][id]"] = survey.items[i].id
parameters["items[\(i)][note]"] = survey.items[i].note
}
或者,您也可以这样做:
var parameters = [String:AnyObject]()
for var i = 0; i < survey.items.count; i++ {
parameters["items[\(i)]"] = ["id" : survey.items[i].id, "note" : survey.items[i].note]
}
提交请求时,请务必检查错误,例如:
Alamofire.request(.POST, url, parameters: parameters)
.responseJSON { response in
switch (response.result) {
case .Failure(let error):
print("error: \(error)")
case .Success(let responseObject):
print("responseObject: \(responseObject)")
}
}
-
你说以下是有效的:
parameters["items"] = [[ "id": 4, "note": "Pen" ]]
生成一个看起来像的主体:
items%5B%5D%5Bid%5D=4&items%5B%5D%5Bnote%5D=Pen
当删除百分比转义时,看起来像:
items[][id]=4&items[][note]=Pen
而上面的例子生成:
items%5B0%5D%5Bid%5D=4&items%5B0%5D%5Bnote%5D=Pen
即:
items[0][id]=4&items[0][note]=Pen
在我解释您的Android代码时,后者应该是正确的格式。我无法将您的Android代码与测试结果进行协调。