我在服務器和客戶端之間存在問題。我在PHP Symfony的服務器端有一個Rest API。 服務器端:PHP Symfony API和jQuery Ajax請求
/**
* @Route("/advertisement/all", name="advertisement_get_all")
* @Method("POST")
*/
public function getAllAdvertisement()
{
header('Content-Type: application/json');
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
$content = $this->get("request")->getContent();
$advertisemenetService = $this->container->get("advertisementservices");
$response = $advertisemenetService->getAllAdvertisement($content);
} else {
$response = new \stdClass();
$response->error = true;
$response->message = "Error occurred: You aren't authorized!";
}
return new JsonResponse($response);
}
如果我嘗試在DHC REST客戶端Chrome擴展爲 development.domain.com/index.php/api/v2/advertisement/all
與內容類型:application/x-www-form-urlencoded
我得到了一個正確的JSON對象。如果我嘗試同樣與application/json
symfony的說,下面的錯誤對我來說: Failed to start the session because headers have already been sent by "" at line 0. (500 Internal Server Error)
JSON response example
客戶端:
我如何在API測試我有一個正確的JSON對象表示。我的客戶端代碼:
function sendAjaxRequest(method, url, data, contentType) {
var response;
$.ajax({
method: method,
url: url,
data: data,
dataType: 'json',
contentType: contentType,
success: function(msg) {
response = msg;
}
});
return jQuery.parseJSON(response);
}
response = sendAjaxRequest("POST", "{{ path('advertisement_get_all') }}", '', 'application/x-www-form-urlencoded');
document.getElementById("loader-container").innerHTML = response;
在這種情況下,我總是在客戶端獲得undefined
。我嘗試在響應中使用JSON.stringify,因爲它是一個JSON對象。
當您使用'JsonResponse'時,您不想添加'header'函數。註釋行:'header('Content-Type:application/json');' – bobo