2016-11-18 111 views
0

我在服務器和客戶端之間存在問題。我在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對象。

+3

當您使用'JsonResponse'時,您不想添加'header'函數。註釋行:'header('Content-Type:application/json');' – bobo

回答

0

我扔掉了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響應更早運行。

1

將loader-container的更新移動到成功處理程序中。

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); 
     } 
    }); 
} 
+0

基本上我使用了XMLHttpRequest的相同解決方案。這也是一個很好的解決方案,但對我來說這是一個小錯誤,這就是爲什麼我將它改爲舊的解決方案。 – PumpkinSeed