【发布时间】:2018-06-07 17:41:06
【问题描述】:
我有一个小项目,我正在尝试做一些用户可以将一些数据输入到文本框中,然后将其发送到 php 服务器,我以前没有使用 angular,但我现在使用它尝试将 angular 和 php 结合使用。
我的问题是,一旦我点击“提交”,发送到 .txt 文件的数据要么使用 $_POST 打印“数组”,要么使用 $_HTTP_RAW_POST_DATA 不打印任何内容。
app.component.ts:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
data: string;
userInput: any;
@ViewChild('toSend') input: ElementRef;
constructor(private http: HttpClient) {
}
toSend = JSON.stringify(this.input);
ngOnInit(): void {
}
postData() {
const newInput = {
text: this.input.nativeElement.value
};
console.log(this.input.nativeElement.value);
this.http.post('http://localhost:81/test.php', this.toSend)
.subscribe(
res => {
console.log(res);
}
);
}
requestData() {
this.http.get('http://localhost:81/test.php').subscribe(
data => {
const myJSON = JSON.stringify(data);
console.log(myJSON);
}
);
}
}
php:
<?php
echo $_POST;
$myfile = fopen("TestingOut.txt", "a++") or die("Unable to open file!");
$txt = $HTTP_RAW_POST_DATA."\r\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
app.component.html:
<div style="text-align: center; padding-top: 10px">
<input type="text"
id="inputText"
placeholder="Insert Input"
#toSend
>
<p></p>
<button type='submit' (click)='postData()' >Submit Data</button>
<br>
<hr>
<button (click)='requestData()'>Request Data</button>
</div>
【问题讨论】:
-
试着写 dd($_POST);在 php 端而不是 echo $_POST;这样您就可以了解您收到的内容的结构
标签: php angular angular-httpclient