2014-10-30 88 views
3

我送使用jQueryCodeception - POST生JSON字符串

var url = 'http://site.local/api/package/create'; 
var data = { 
    "command": "package", 
    "commandParameters": { 
    "options": [ 
     { 
     "a": true 
     } 
    ], 
    "parameters": { 
     "node_id": 1111, 
     "node_name": "Node Name" 
    } 
    } 
} 
$.ajax({ 
    url: url, 
    type: "POST", 
    data: JSON.stringify(data), 
    contentType: "application/json", 
    success: function (a, b, c) { 
     // Do something with response 
    } 
}); 

也在做類似使用的東西下面的請求郵差(瀏覽器插件)

POST 
Content-Type: application/json 
Payload: 
{ 
     "command": "package", 
     "commandParameters": { 
     "options": [ 
      { 
      "a": true 
      } 
     ], 
     "parameters": { 
      "node_id": 1111, 
      "node_name": "Node Name" 
     } 
     } 
    } 

意圖是給我寄了原始JSON字符串到我的服務器,而不是讓Jquery將其轉換爲發佈數據。 如何執行Codeception一樣的,我只是不能看到它的文檔中,我只看到下面..

$I->sendAjaxPostRequest('/updateSettings', array('notifications' => true)); 

所以我想我想在Codeception POST請求,同時連接JSON在請求的正文中?

回答

7

encodeApplicationJson功能codeception/src目錄/ Codeception /模塊/ REST.php檢查頭「Content-Type」和值「application/json」是否存在。

如果設置返回json_encode($參數),這是一個字符串,這是我想要什麼,所以我最終會做這樣的事情...

$I->haveHttpHeader('Content-Type', 'application/json'); 
    $I->sendPOST('api/package/create', [ 
     'command' => 'package', 
     'commandParameters' => [ 
      'options' => [], 
      'arguments' => [] 
     ] 
    ]); 
    $I->canSeeResponseCodeIs(200); 
    $I->seeResponseIsJson(); 

之間的差別的一些信息sendpostsendajaxpostrequest

http://phptest.club/t/what-is-the-difference-between-sendpost-and-sendajaxpostrequest/212#post_2

2

我想你應該告訴jQuery不要處理你傳遞的數據。 試試這個

$.ajax({ 
    url: url, 
    type: "POST", 
    processData: false, 
    data: JSON.stringify(data), 
    contentType: "application/json", 
    success: function (a, b, c) { 
     // Do something with response 
    } 
}); 

在PHP端你可以使用下面的代碼來獲取原始數據

$rawdata = file_get_contents('php://input'); 
+0

這工作完全適合我,謝謝! – DethRaid 2017-04-15 02:48:25