post请求的键值对怎么写?

来源:8-5 本章实战上

Niweisi

2017-05-13

this.dataSource = this.http.post(this.url,JSON.stringify({username: 'user1'}),{search:mySearch,headers:myHeaders}).map((res) => res.json());

请问post请求的键值对怎么写?JSON.stringify({username: 'user1'})这种写法发送的是json格式,php的$_POST['username']根本接收不到,求解!

写回答

1回答

Niweisi

提问者

2017-05-13

解决了,在发送post请求的时候,请求头

myHeaders.append('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');

一定是这个,否则php接收不到。

其次,JSON.stringify({username: 'user1'})这种写法是不行的,要写成string类型的'sername=hehe&password=aaaaaa',也就是发送get请求的URLSearchParams。

代码片段如下:

  dataSource:Observable<any>;
  http_test:Array<any> = [];

  url:string;
  url2:string;

  constructor(private http:Http) {
      let myHeaders:Headers = new Headers();
      let mySearch:URLSearchParams = new URLSearchParams();

      myHeaders.append("Authorization","Basic 123456");//请求头
      
      //有这条php的$_POST方法才能接收到
      myHeaders.append('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
      
      //get参数
      mySearch.append('username',"hehe");
      mySearch.append('password',"aaaaaa");
      
      this.url = '/api/json.php';
      this.url2 = '/assets/test.txt';
      
      //get请求
      this.dataSource = this.http.get(this.url,{search:mySearch,headers:myHeaders})
          .map((res) => res.json());
          
      //post请求
      this.dataSource = this.http.post(this.url,mySearch,{search:mySearch,headers:myHeaders}).map((res) => res.json());
      
      //mySearch的结果实际上就是username=hehe&password=aaaaaa,这样的string类型的字符串
  }

  ngOnInit() {
      this.dataSource.subscribe(
          (data) => this.http_test = data
      );

  }


0
0

Angular4.0从入门到实战 打造股票管理网站

Angular新特性,教你熟练使用 Angular 和 Typescript 开发组件式单页应用

2683 学习 · 1361 问题

查看课程