2010-06-17 21 views
9

Quando si effettua una chiamata ajax, quando contentType è impostato su application/json invece del predefinito x-www-form-urlencoded, il lato server (in PHP) non può ottenere i parametri del post.
nel seguente esempio di lavoro, se imposto il contentType su "application/json" nella richiesta ajax, PHP $ _POST sarebbe vuoto. perché succede? Come posso gestire una richiesta dove contentType è application/json correttamente in PHP?handle json request in PHP

$.ajax({ 
    cache: false, 
    type: "POST", 
    url: "xxx.php", 
    //contentType: "application/json", 
    processData: true, 
    data: {my_params:123}, 
    success: function(res) {}, 
    complete: function(XMLHttpRequest, text_status) {} 
}); 

risposta

25
<?php 
    var_dump(json_decode(file_get_contents('php://input'))); 
?> 
+0

sì, questo funziona! la discarica i dati della richiesta che ho passato tramite POST – user157195

3

Troverete tipi MIME non riconosciuti in $HTTP_RAW_POST_DATA. Puoi anche forzare PHP a compilare sempre questo array (non solo per i tipi MIME non riconosciuti) impostando la direttiva php.ini always_populate_raw_post_data su true.

dati post grezzi saranno altrimenti disponibili attraverso l'involucro ingresso php://input

Per ulteriori informazioni:

http://us.php.net/manual/en/wrappers.php.php

http://php.net/manual/en/reserved.variables.httprawpostdata.php

http://www.php.net/manual/en/ini.core.php#ini.always-populate-raw-post-data

1

sopra è tecnicamente corretta, ma poiché Non scrivo molto PHP, questo mig HT essere più utile

xxx.php sarebbe

<?php 
$file = fopen("test.txt","a"); 
$post_json = file_get_contents("php://input"); 
$post = json_decode($post_json, true); 
foreach($post as $key=>$value) { 
    $message = $key . ":" . $value . "\n"; 
    echo fwrite($file,$message); 
} 
fclose($file); 
?> 

e poi si può provare con

curl -X POST -H "Content-Type: application/json" -d '{"fieldA":"xyz","fieldN":"xyz"}' http://localhost/xxx.php