2016-11-06 14 views
0

我建立結構如下API:

  • 方法POST
  • URI /words
  • body {"word":"example"}

這個請求應該添加到數據庫的話,如果我測試它的httpie一切都很好。

$ http POST localhost:8000/words word="new word2" 

HTTP/1.1 200 OK 
Access-Control-Allow-Headers: application/json 
Access-Control-Allow-Origin: http://localhost:8080 
Connection: close 
Content-Type: application/json 
Host: localhost:8000 
X-Powered-By: PHP/7.0.12-1+deb.sury.org~xenial+1 
{ 
    "test": { 
     "method": "POST", 
     "input": { 
      "word": "new word2" 
     }, 
     "post": [] 
    }, 
    "words": { 
     "id": "581f2f118b0414307476f7b3", 
     "word": "new word2" 
    } 
} 

test我放在php獲得通過變量:

$method = $_SERVER['REQUEST_METHOD']; 
$input = json_decode(file_get_contents('php://input'),true); 
$post = $_POST; 

我們可以看到,$_POST是空的。如果我使用JavaScript:

$(form).submit(function(e) { 
    var url = "http://localhost:8000/words"; 
    var data = {"word" : form.elements["word"].value }; 
    $.ajax({ 
     type: "POST", 
     url: url, 
     data: data, 
     dataType: 'json', 
     success: function(data) 
     { 
      console.log(JSON.stringify(data)); 
     } 
    }); 
    e.preventDefault(); 
}); 

我獲得以下控制檯日誌:

{ 
    "test":{ 
     "method":"POST", 
     "input":null, 
     "post":{ 
     "word":"word from form" 
     } 
    }, 
    "words":{ 
     "id":"581f34b28b0414307476f7b6", 
     "word":null 
    } 
} 

現在input是空的。單詞爲空,因爲我正在處理$input["word"],從php://input。我的問題:

  • 我應該處理$_POST,還是同時檢查兩個變量?
  • 如何使用這些方法的最佳實踐?
  • 我可以從瀏覽器發送php://input或從命令行收費$_POST發送httpie

回答

0

您手動構建的示例和您的JavaScript示例不等效。

在第一個發送JSON編碼數據與application/json內容類型。

第二,您將JavaScript對象傳遞給jQuery,並允許它遵循默認行爲,即使用application/x-www-form-urlencoded格式對其進行編碼並將其用作內容類型(就像提交一個普通的HTML表單一樣)。

PHP在POST請求中支持application/x-www-form-urlencoded數據,但不支持JSON。

我應該處理$ _POST,還是檢查兩個變量?

如果您要發送application/x-www-form-urlencoded數據或PHP支持的其他格式,請使用$_POST。否則,您需要從php://input獲取原始數據並自行解析。

我可以發送PHP:從瀏覽器

//輸入見POST data in JSON format

$ _ POST命令行toll樣httpie?

the httpie documentation

http --form POST api.example.org/person/1 name='John Smith' 
+0

哇!很好的答案!比你非常。 – Daniel