我想將我的angular2應用程序連接到我的PHP後端。理想我想這樣做:閱讀PHP中的Angular2 POST數據
this.http.post('/users/create', {email: email, password: password});
的問題是,當我做到這一點我$_POST
是PHP空。我該做些什麼才能做到這一點?
我想將我的angular2應用程序連接到我的PHP後端。理想我想這樣做:閱讀PHP中的Angular2 POST數據
this.http.post('/users/create', {email: email, password: password});
的問題是,當我做到這一點我$_POST
是PHP空。我該做些什麼才能做到這一點?
Angular的http實現將數據作爲application/json
負載發送。閱讀從PHP這樣的數據,你必須使用這種代碼:
$data = json_decode(file_get_contents("php://input"));
// you can even override the `$_POST` superglobal if you want :
$_POST = json_decode(file_get_contents("php://input"));
如果你想發送的數據爲
application/x-www-form-urlencoded
,然後可以從PHP的
$_POST
超全局讀它沒有任何變化到你的服務器代碼
,你需要編碼你的數據。
const body = new URLSearchParams();
Object.keys(value).forEach(key => {
body.set(key, value[key]);
}
let headers = new Headers();
headers.append('Content-Type','application/x-www-form-urlencoded');
this._http.post(this._contactUrl, body.toString(), {headers}).subscribe(res => console.log(res));
我的意思是用jQuery例如它與$ _ POST和JSON對象
它不使用JSON對象的工作,如果你可以通過$_POST
讀取數據,這意味着它已經被作爲application/x-www-form-urlencoded
,不application/json
,參數設置爲純JS對象,但...
有沒有什麼方法可以通過每個請求來完成這項工作?當我覺得每個PHP應用程序都應該有這個問題時,我感到很困惑,這是一件很麻煩的事情?如果他們想與angularjs – DannySwekker
一起工作,只需創建一個自定義服務,它將包裝'http'調用。我不認爲這是一個問題,因爲mot人們使用JSON API與服務器通信。 – n00dl3
您可以使用PHP:此
//輸入後數據用angular2這樣和json_decode$arr = json_decode(file_get_contents('php://input'),TRUE);
echo "<pre>";print_r($arr);exit;
所以通過這個$ arr打印整個文章數組,並在任何你想要的地方使用它。
很好的解釋在這裏: http://stackoverflow.com/questions/36897266/fetch-and-insert-data-into-mysql-using-angularjs –
那不可能是唯一的解決辦法嗎?從php://輸入中讀取?我的意思是用jQuery例如它可以處理'$ _POST'和'json'對象 – DannySwekker
@DannySwekker - 默認情況下,jQuery不會將請求格式設置爲JSON。它使用application/x-www-form-urlencoded編碼。你也應該[清除你對JSON的明顯誤解](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/)。 – Quentin