2017-05-04 91 views
7

我想發送一個POST請求到我的PHP文件來處理它,並將數據存儲在數據庫中..我相當堅持它,因爲$ _POST保持空無論我嘗試..ReactJS&Axios/PHP - 發送POST請求

有人可以幫我發送一個帖子請求,並幫助我如何處理它?

我愛可信要求:

// Performing a POST request 
axios.post('dev/api/post.php',{ text: text, unk: unk}) 
    .then(function(response){ 
     console.log(response); 
}).catch(function (error) { 
     console.log(error); 
}); 

而這就是我還挺試圖在PHP中,一些代碼被註釋掉了,因爲不知道它的工作..

if(isset($_POST) && !empty($_POST)){ 
/* 
$jsonReceiveData = json_encode($_POST); 
$json_output = json_decode($jsonReceiveData); 
$task = $json_ouput->text; 
$uniquekey = $json_output->unk; 
*/ 
echo $_POST; 
/* 
$stmt = $pdo->prepare("INSERT INTO todo (id, tekst, uniquekey) VALUES ('', :tekst, :unk)"); 
$stmt->bindParam(':unk', '1'); 
$stmt->bindParam(':tekst','testing'); 
$stmt->execute(); 
*/ 

}

SOLUTION:

$data = json_decode(file_get_contents("php://input"), true); 
$task = $data['text']; 

的對象是在PHP中發現://輸入

+0

您的axios請求語法看起來正確,假設{text:text,unk:unk} tetxt和unk在其中有數據,您的api端點是否正確? – David

+0

$ _POST是一個數組,回聲將不起作用,嘗試print_r($ _ POST) –

+0

@David可能我的端點不正確,但是如何處理Axios發佈的PHP中的JSON對象?我不知道如何在PHP中訪問它 –

回答

0

用戶解決了PHP時,「發現」的對象://輸入

$data = json_decode(file_get_contents("php://input"), true); 
$task = $data['text']; 

正如指出的STEEL,這是一個問題,在PHP代碼,不是React或Axios。