我正在尝试使用Angular2,MySQL和PHP设置CRUD系统,我可以使用以下代码获取我的数据:
getClients(){
this.http.get('http://localhost/Angular%20tests/pr1/getClients.php')
.subscribe(res=>this.clients=res.json(),
error=> alert("Error get clients"),
()=> console.log("Get clients completed..."));
}
但是为了将数据发送到服务器,我不明白是我的错误,前三条说明是正确的条目值。
onPersonneF(f:NgForm){
console.log(f.value);
console.log(JSON.stringify(f.value));
console.log(f.valid);
// test for the post
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
this.http.post('http://localhost/Angular%20tests/pr1/insertClient.php', JSON.stringify(f.value), options);
}
我的php文件的代码是:
<?php
// for: Blocage d'une requête multi-origines (Cross-Origin Request)
header("Access-Control-Allow-Origin: *");
try {
$pdo = new PDO("mysql:host=localhost; dbname=test; char=utf8", '****', '****');
} catch (Exception $e) {
echo "Connexion Error".$e->getMessage();
}
$data = json_decode(file_get_contents("php://input"));
//var_dump($data);
echo "**************";
echo $data->nom_client;
echo "**************";
$nom_client = $data->nom_client;
$prenom_client = $data->prenom_client;
$no_order = $data->no_order;
$query = $pdo->prepare("insert into clients values(NULL,'".$nom_client."', '".$prenom_client."', '".$no_order."')");
$query->execute();
$query->closeCursor();
?>
答案 0 :(得分:1)
请勿将其作为JSON发送,而是将URLSearchParams
和标题用作application/x-www-form-urlencoded
。
onPersonneF(f:NgForm){
let body = new URLSearchParams();
// obviously set your correct parameters
body.set('myPropertyName', f.myProperty)
// the rest of data to send...
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
this.http.post('http://localhost/Angular%20tests/pr1/insertClient.php', body.toString(), options)
.map(res => res.json());
.subscribe(data => console.log(data)) // do subscription in component
}
然后你可以在你的php文件中找到你的数据......在这里我只是重新搜索数据。请记住json_encode
您要归还的内容:)
<?php
header("Access-Control-Allow-Origin: *");
$data = file_get_contents("php://input");
echo json_encode($data);
?>