简体   繁体   English

PHP Symfony API和jQuery Ajax请求

[英]PHP Symfony API and jQuery Ajax request

I have a problem between server and client side. 我在服务器端和客户端之间有问题。 I have a Rest API on server side with PHP Symfony. 我在服务器端使用PHP Symfony拥有Rest API。 Server-side: 服务器端:

/**
* @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);
}

If I try it in DHC Rest Client Chrome Extension for that development.domain.com/index.php/api/v2/advertisement/all with Content type: application/x-www-form-urlencoded I got a proper JSON object. 如果我在DHC Rest Client Chrome扩展程序中针对该development.domain.com/index.php/api/v2/advertisement/all尝试使用内容类型: application/x-www-form-urlencoded得到一个正确的JSON对象。 If I try the same with application/json the symfony say the following error for me: Failed to start the session because headers have already been sent by "" at line 0. (500 Internal Server Error) JSON response example 如果我对application/json尝试相同的操作,则symfony会为我说以下错误: Failed to start the session because headers have already been sent by "" at line 0. (500 Internal Server Error) JSON响应示例

Client-side: 客户端:

How I said on the API tester I got a proper JSON object. 我在API测试仪上怎么说,我有一个正确的JSON对象。 My clientside code: 我的客户端代码:

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;

In this case I always get undefined on the client-side. 在这种情况下,我总是在客户端无法undefined I try to use the JSON.stringify on the response, because it is a JSON object. 我尝试在响应上使用JSON.stringify,因为它是JSON对象。

Move the update of the loader-container into the success handler. 将装载程序容器的更新移到成功处理程序中。

function sendAjaxRequest(method, url, data, contentType) {
    var response;
    $.ajax({
        method: method,
        url: url,
        data: data,
        dataType: 'json',
        contentType: contentType,
        success: function(msg) {
            document.getElementById("loader-container").innerHTML = JSON.parse(msg);
        }
    });
}

I throw away the jQuery Ajax, because it was too dificult to slow this problem, and got back to the XMLHttpRequest and using a callback function which I called when the AJAX getting the response. 我扔掉了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;
}

The main problem, which occured: The response handler function always run sooner than the Ajax response arrived. 出现的主要问题是:响应处理程序功能总是比Ajax响应到达早运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM