2016-02-10 29 views
6

cerco di inviare i dati da angolare 2 a PHP:Messaggio JSON da angolare 2 a 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); 
}); 

In angolare 2 si possono inviare solo stringa come dati e non JSON? Va bene per me, ma faccio fatica a ottenere i dati pubblicati su php. Ho provato $obj = $_POST['order'];

+1

PHP si aspetta dati di post ad essere in chiave '= coppie valore' quando si sta costruendo $ _POST. non l'hai inviato, hai inviato una stringa json raw, che è fondamentalmente solo il componente 'value'. dal momento che non esiste la chiave 'key', php non può mettere nulla in' $ _POST', perché un elemento dell'array deve avere una chiave. probabilmente potresti recuperare il json leggendo da 'php: // input'. –

risposta

8

Marc B è corretto, tuttavia ciò che sta accadendo è che l'array $ _POST conterrà un valore vuoto con un set di chiavi per la stringa JSON si sta passando ...

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

You " possono" afferrare che (anche se questo sarebbe l'approccio sbagliato) ottenendo la chiave utilizzando ...

key($_POST) 

ad esempio:

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

MA che cosa si può fare è inviare i dati come coppie di valori chiave:

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

Poi in PHP si può afferrare i dati utilizzando:

$_POST['order'] 

Poche cose da notare:

  • cambiato intestazione Content-Type in application/x-www-form-urlencoded (più per i miei test, poiché questo non richiede alcuna verifica preliminare)
  • avviso che ordine è una coppia di valori stringa chiave, invece di JSON
  • avviso che ordine in this.http.post è sempre passato come è, senza JSON.stringify
+0

Grazie ha funzionato per me :) 4 ore di ricerca finalmente :) – Jestin

+0

@inki: let order = 'order = foobar'; invia un dato. Potete per favore aiutarmi ad inviare più dati. Puoi per favore darmi la sintassi. –

+2

@GreenComputers fai come = 'order = foobar & anotherkey = anothervalue & key3 = value3' Separa le tue variabili usando & sign –

3

faccio non so se è una cattiva pratica ma mi sembra giusto, anche se mi dà fastidio un po 'di

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

const obj = { nome: 'gabriel', age: 20 }; 
const body = 'data=' + JSON.stringify(obj); 

this.http.post('/test.php', body, { headers }) 
    .subscribe(res => console.log(res.json()), res => console.error(res)) 

E in php

$post = json_decode($_POST['data']);