Php 在服务器上以表单变量发布json对象
你好,我正在IOS SWIFT 2上工作。我需要在一个变量中发送json对象,以便像这样访问json对象Php 在服务器上以表单变量发布json对象,php,ios,arrays,json,swift,Php,Ios,Arrays,Json,Swift,你好,我正在IOS SWIFT 2上工作。我需要在一个变量中发送json对象,以便像这样访问json对象 $json = $_POST['json']; $data = json_decode($json, TRUE); $email = $data['email']; $user_password = $data['password']; 现在数据正在像这样发布到服务器上 { "email" : "email", "p
$json = $_POST['json'];
$data = json_decode($json, TRUE);
$email = $data['email'];
$user_password = $data['password'];
现在数据正在像这样发布到服务器上
{
"email" : "email",
"password" : "password"
}
这是我正在使用的代码
func post() {
let url:String = "http://example.com/test.php"
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let params = ["email":"email", "password":"password"] as Dictionary<String, String>
//let request = NSMutableURLRequest(URL:url)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
do {
let data = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
print("dataString is \(dataString)")
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
} catch {
//handle error. Probably return or mark function as throws
print(error)
return
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// handle error
guard error == nil else { return }
print("Response: \(response)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
let json: NSDictionary?
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
} catch let dataError {
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
print(dataError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
// return or throw?
return
}
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
let success = parseJSON["success"] as? Int
print("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)
print("Error could not parse JSON: \(jsonStr)")
}
})
task.resume()
}
func post(){
让url:String=”http://example.com/test.php"
let request=NSMutableURLRequest(URL:NSURL(string:URL)!)
让params=[“email”:“email”,“password”:“password”]作为字典
//let request=NSMutableURLRequest(URL:URL)
let session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
做{
let data=尝试NSJSONSerialization.dataWithJSONObject(参数,选项:。预打印)
让dataString=NSString(数据:data,编码:NSUTF8StringEncoding)!
打印(“数据字符串为\(数据字符串)”)
request.HTTPBody=尝试NSJSONSerialization.dataWithJSONObject(参数,选项:。预打印)
}抓住{
//处理错误。可能将函数返回或标记为抛出
打印(错误)
回来
}
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
让task=session.dataTaskWithRequest(请求,completionHandler:{data,response,error->Void in
//处理错误
保护错误==nil else{return}
打印(“响应:\(响应)”)
让strData=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“正文:\(标准数据)”)
让json:NSDictionary?
做{
json=尝试NSJSONSerialization.JSONObjectWithData(data!,选项:.MutableLeaves)作为NSDictionary
}捕获let数据错误{
//JSONObjectWithData构造函数是否返回错误?如果是,请将错误记录到控制台
打印(数据错误)
让jsonStr=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“错误无法分析JSON:'\(jsonStr)'”)
//回击还是投掷?
回来
}
//JSONObjectWithData构造函数没有返回错误。但是,我们仍然应该
//使用可选绑定检查并确保json具有值。
如果让parseJSON=json{
//好的,parsedJSON在这里,让我们从中获得“成功”的价值
让success=parseJSON[“success”]作为?Int
打印(“成功:\(成功)”)
}
否则{
//哇,好吧,json对象为零,出现了问题。可能服务器没有运行?
让jsonStr=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“错误无法解析JSON:\(jsonStr)”)
}
})
task.resume()
}
我想以一个名为“json”的形式变量传递上面的json。我强烈建议使用一个库,例如来处理这个问题。 自己做这件事很乏味 添加到Swift项目后,您可以非常非常优雅地发送JSON参数: Github页面中的示例: 然后可以使用现有的PHP代码来处理JSON 编辑: 处理JSON也非常优雅:
Alamofire.request(.POST, url, etc).responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Alamofire.request(.POST, url, etc).responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}