将JSON从angular 2发布到php [英] Post JSON from angular 2 to php

查看:88
本文介绍了将JSON从angular 2发布到php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将数据从angular 2发布到php:

I try to post data from angular 2 to php:

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

this.http.post('http://myserver/processorder.php', JSON.stringify(order), {
    headers: headers
}).subscribe(res => {
    console.log('post result %o', res);
});

在角度2中,只能将字符串发布为数据,而不能发布Json吗?对我来说还可以,但是我很难在php上获取发布的数据.我尝试了$obj = $_POST['order'];

In angular 2 one can only post string as data and not Json? That's ok for me but I struggle to get the posted data on php. I tried $obj = $_POST['order'];

推荐答案

Marc B是正确的,但是正在发生的事情是$ _POST数组将包含一个空值,其键集设置为您要传递的JSON字符串.

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)

例如:

$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);
});

然后在PHP中,您可以使用以下方法获取数据:

Then in PHP you can grab the data using:

$_POST['order']

几件事要注意:

  • 已将标头Content-Type更改为application/x-www-form-urlencoded(更多内容用于我自己的测试,因为这不会执行任何预检请求)
  • 请注意,订单是键值对字符串,而不是JSON
  • 请注意,此.http.post中的 order 已按原样传递而没有JSON.stringify
  • 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

这篇关于将JSON从angular 2发布到php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆