【发布时间】:2016-11-18 10:18:09
【问题描述】:
我在服务器端和客户端之间有问题。我在服务器端有一个使用 PHP Symfony 的 Rest API。 服务器端:
/**
* @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 Client 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');
标签: javascript php jquery json symfony