我查看了许多材料并使用了很多方式将json数据发送到php服务器。首先,我创建了singleORder的顺序并在arrayOfOrders中收集它:
func createOrderInArray(){
var savedDataHourly: NSDictionary
var savedDataTransfer:NSDictionary
var savedDataReis: NSDictionary
var singleOrderClass = Order()
//localArrayOfOrder = []
singleOrderClass.type_id = singleStructDataOfCar.typeID
singleOrderClass.model_id = singleStructDataOfCar.modelID
// loading hourly
if Load.dictionary("ServiceByHours") != nil {
savedDataHourly = Load.dictionary("ServiceByHours")
println("loading hourly")
singleOrderClass.hourly.addressOfRequest = savedDataHourly["ServiceByHoursAddressOFRequest"] as String
singleOrderClass.hourly.addressOfDelivery = savedDataHourly["ServiceByHoursAddressOfDelivery"] as String
singleOrderClass.hourly.detailedText = savedDataHourly["ServiceByHoursDetailText"] as String
singleOrderClass.hourly.startofWork = savedDataHourly["StartDate"] as String
singleOrderClass.hourly.endOfWork = savedDataHourly["EndDate"] as String
singleOrderClass.hourly.undefinedTime = savedDataHourly["undefinedTime"] as String
}else{
println("hourly is empty")
singleOrderClass.hourly.addressOfRequest = ""
singleOrderClass.hourly.addressOfDelivery = ""
singleOrderClass.hourly.detailedText = ""
singleOrderClass.hourly.startofWork = ""
singleOrderClass.hourly.endOfWork = ""
singleOrderClass.hourly.undefinedTime = ""
}
// loading transfer
if Load.dictionary("ServiceByTransfer") != nil {
savedDataTransfer = Load.dictionary("ServiceByTransfer")
singleOrderClass.transfer.startofWork = savedDataTransfer["ServiceDataStartDate"] as String
singleOrderClass.transfer.addressOfRequest = savedDataTransfer["ServiceDataAddressOfReq"] as String
singleOrderClass.transfer.addressOfDelivery = savedDataTransfer["ServiceDataAddressOfDel"] as String
singleOrderClass.transfer.detailedText = savedDataTransfer["ServiceDataDetailedText"] as String
}else{
singleOrderClass.transfer.startofWork = ""
singleOrderClass.transfer.addressOfRequest = ""
singleOrderClass.transfer.addressOfDelivery = ""
singleOrderClass.transfer.detailedText = ""
}
// loading reis
if Load.dictionary("ServiceByReis") != nil {
savedDataReis = Load.dictionary("ServiceByReis")
singleOrderClass.custom.startofWork = savedDataReis["ServiceDataStartDate"] as String
singleOrderClass.custom.addressOfRequest = savedDataReis["ServiceDataAddressOfReq"] as String
singleOrderClass.custom.addressOfDelivery = savedDataReis["ServiceDataAddressOfDel"] as String
singleOrderClass.custom.detailedText = savedDataReis["ServiceDataDetailedText"] as String
singleOrderClass.custom.priceProposed = savedDataReis["ServiceDataPrice"] as String
}else{
singleOrderClass.custom.startofWork = ""
singleOrderClass.custom.addressOfRequest = ""
singleOrderClass.custom.addressOfDelivery = ""
singleOrderClass.custom.detailedText = ""
singleOrderClass.custom.priceProposed = ""
}
// add this single order to array
arrayOfOrders.append(singleOrderClass)
}
我只收集一个数组中的所有订单。下一步是将数组中的所有数据转换为Dictionary,以便将其序列化为json格式:
func createJsonFromArrayToDict(orders: [Order])->[AnyObject]{
//as Dictionary<String, String>
var dictOfOrders: [AnyObject] = []
var counter = 0
for singleOrder in orders {
counter = counter + 1
println("COUNTER: \(counter)")
var dicOfOrder = [
"type_id": singleOrder.type_id,
"model_id": singleOrder.model_id,
"transfer": [
"StartDate": singleOrder.transfer.startofWork,
"StartPoint": singleOrder.transfer.addressOfRequest,
"EndPoint": singleOrder.transfer.addressOfDelivery,
"CommentText": singleOrder.transfer.detailedText
],
"hourly": [
"StartDate": singleOrder.hourly.startofWork,
"EndDate": singleOrder.hourly.endOfWork,
"StartPoint": singleOrder.hourly.addressOfRequest,
"EndPoint": singleOrder.hourly.addressOfDelivery,
"CommentText": singleOrder.hourly.detailedText,
"Undefined_Time": singleOrder.hourly.undefinedTime
],
"custom":[
"StartDate": singleOrder.custom.startofWork,
"StartPoint": singleOrder.custom.addressOfRequest,
"EndPoint": singleOrder.custom.addressOfDelivery,
"CommentText": singleOrder.custom.detailedText,
"customPrice": singleOrder.custom.priceProposed
],
"device_name": "ios_device"
]
// check if it is not the same order as previous (need to include this in future)
dictOfOrders.append(dicOfOrder)
}
return dictOfOrders
}
现在我使用此函数将此JSON发送到服务器:
func sendJsonToServer(OrderList: AnyObject){
var request = NSMutableURLRequest(URL: NSURL(string: "osc.kz/ru/test")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
if let serializedData = NSJSONSerialization.dataWithJSONObject(OrderList, options: nil, error: &err){
request.HTTPBody = serializedData
println(request.HTTPBody)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as NSArray
// var json = noWrappedJson!
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
for singleCode in json {
if let parseJSON = singleCode as? NSDictionary {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
var success = parseJSON["code"] as? String
println("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
}
})
task.resume()
}
但是,我的服务器正在获取空数组[]。我无法弄清楚为什么我发送空值。在发送请求之前我打印了request.httpbody。它有一个值,但服务器得到[]。任何建议表示赞赏!
服务器端在PHP上:
<?php
if ($_REQUEST)
{ $_ARR = $_REQUEST;
$OrderList = $_ARR['OrderList'];
foreach($OrderList as $order){
$auto_type_id = $order['type_id'];
$auto_model_id = $order['model_id'];
$device_name = $order['device_name'];
$commentText = $order['commentText'];
$transfer = '';
$hourly = '';
$custom = '';
if (!empty($order['transfer'])) {
$transfer = $order['transfer'];
$db->query("insert into table_test_android set json_text = 'transfer' ");
$db->query("insert into table_test_android set json_text = 'type:".$auto_type_id.",model_id:".$auto_model_id.",device:".$device_name."' ");
}
if (!empty($order['hourly'])) {
$hourly = $order['hourly'];
$db->query("insert into table_test_android set json_text = 'hourly' ");
$db->query("insert into table_test_android set json_text = 'type:".$auto_type_id.",model_id:".$auto_model_id.",device:".$device_name."' ");
}
if (!empty($order['custom'])) {
$custom = $order['custom'];
$db->query("insert into table_test_android set json_text = 'custom' ");
$db->query("insert into table_test_android set json_text = 'type:".$auto_type_id.",model_id:".$auto_model_id.",device:".$device_name."' ");
}
}
$db->query("insert into table_test_android set json_text = '".json_encode($_ARR)."'");
$code_my = mt_rand(100000, 999999);
$code[] = array('code'=>(string)$code_my);echo json_encode($code);
}
答案 0 :(得分:2)
如果您要发送json数据,则不会填充phps superglobals - 访问您需要访问原始输入流的json:
$json = file_get_contents('php://input');
//echo $json shoulkd show the json string
$array = json_decode($json, true);
// var_dump($arr) should show the array structure
$OrderList = $array['OrderList'];
//provided your json is structured correctly everything else should work from here on
编辑您可能还有许多其他问题,因为启动您的SQL是错误的 - INSERT语法看起来像'INSTERT into tablename (colname, anothercolname) VALUES (val,val);'
而您有一个奇怪的插入/更新mashup,但这超出了这个问题的范围(如何将json数据发送到服务器)
答案 1 :(得分:0)
尽管上面的答案有效,但是您可以尽可能远离“ php:// input”。如果您想将数据数组[String:Any]发送到php API,我建议您执行以下操作:
填充数组[String:Any]。
使用JSONSerialization将数组转换为Data:
JSONSerialization.data(withJSONObject:array,options:[])
创建一个URLRequest并将方法设置为POST:
var request = URLRequest(url:url)
创建字符串变量参数示例:
let parameter =“ postData =” + data.base64EncodedString()///(数据变量来自步骤2)
在URLRequest变量(请求)中,填充httpBody,例如:
request.httpBody = parameter.data(使用:String.Encoding.utf8)
使用URLSession.shared.dataTask发送请求...
在PHP中,使用$ _POST [“ postData”]捕获帖子,然后使用base64_decode解码post参数的值,该参数为您提供json的字符串表示形式,之后您可以使用json_decode()将其转换为一个关联的数组,请参见下文:
$content = $_POST["postData"];
$decodedContent = base64_decode($content);
$json = json_decode($decodedContent, true);