早安朋友
我正在尝试将数据发送到BBDD,但出现错误:
Error Domain = NSCocoaErrorDomain代码= 3840“无值。” UserInfo = {NSDebugDescription =无值。}。搜索信息,发现您应该添加request.addValue(“ application / json”,用于HTTPHeaderField:“ Content-Type”)
,但仍然无法正常工作。如果我尝试使用https://jsonplaceholder.typicode.com/posts的网址,它会起作用。
@IBAction func postTapped(_ sender: Any) {
let paramater = ["Name":"Bob", "Room":"Telomer", "Teacher_Name":"Tomson"]
/*
guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {
return
}
*/
guard let url = URL(string: "http://xxxxxxx/postClasses.php") else {
return
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
guard let httpBody1 = try? JSONSerialization.data(withJSONObject: paramater, options: []) else {
return
}
request.httpBody = httpBody1
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
}
catch{
print(error)
}
}
}.resume()
}
和php
$name= ( empty($_POST['Name']) ) ? NULL : $_POST['Name'];
$room= ( empty($_POST['Room']) ) ? "" : $_POST['Room'];
$Teacher_Name= ( empty($_POST['Teacher_Name']) ) ? "" : $_POST['Teacher_Name'];
if ($name){
if( $conexion=mysqli_connect($hostname,$username,$password,$database) ){
$sql= "INSERT INTO classes(Name,Room,Teacher_Name) VALUES (?,?,?)";
if ($stmt = mysqli_prepare($conexion, $sql)) {
mysqli_stmt_bind_param($stmt, "sss", $name,$room,$Teacher_Name);
if( mysqli_stmt_execute($stmt) ) {
//$msg=printf("Insert", mysqli_stmt_affected_rows($stmt));
$msg=printf("");
}else{
//$msg=printf("Error: %s ok", mysqli_stmt_error($stmt));
$msg=printf("Account already exists");
}
mysqli_stmt_close($stmt);
}else{
$msg=printf("Error: %s ", mysqli_error($conexion));
}
mysqli_close($conexion);
}else{
$msg=printf("Error de conetion: %s", mysqli_connect_error());
}
}else{
$msg="";
}
//echo $msg;
非常感谢您