Post JSON from angular 2 to php

后端 未结 3 1037
难免孤独
难免孤独 2020-12-29 15:06

I try to post data from angular 2 to php:

let headers = new Headers();
headers.append(\'Content-Type\', \'application/json\');
var order = {\'order\': this.o         


        
3条回答
  •  萌比男神i
    2020-12-29 15:30

    Marc B is correct, however what is happening is that the $_POST array will contain an empty value with a key set to the JSON string you are passing...

    Array
    (
        [{"order":"foobar"}] => 
    )
    

    You "can" grab that (although this would be the wrong approach) by getting the key using...

    key($_POST)
    

    for example:

    $obj = json_decode(key($_POST));
    echo $obj->order;
    

    BUT what you can do is send the data as value key pairs:

    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    let order = 'order=foobar';
    
    this.http.post('http://myserver/processorder.php', order, {
        headers: headers
    }).subscribe(res => {
        console.log('post result %o', res);
    });
    

    Then in PHP you can grab the data using:

    $_POST['order']
    

    Few things to note:

    • changed header Content-Type to application/x-www-form-urlencoded (more for my own testing since this doesn't do any preflight requests)
    • notice that order is a key value pair string instead of JSON
    • notice that order in this.http.post is getting passed as-is without JSON.stringify

提交回复
热议问题