我在服务器端和客户端之间有问题。我在服务器端使用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响应示例
客户端:
我在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对象。
我扔掉了jQuery Ajax,因为它很难解决这个问题,然后回到XMLHttpRequest并使用了我在AJAX得到响应时调用的回调函数。
function sendAjaxRequest(method, url, data, contentType, callback)
{
var response
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
response = xhttp.responseText;
callback(JSON.parse(response));
}
};
xhttp.open(method, url, true);
xhttp.setRequestHeader("Content-Type", contentType);
xhttp.send(data);
return response;
}
出现的主要问题是:响应处理程序功能总是比Ajax响应到达早运行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句