简体   繁体   中英

parse JSON working on localhost but not on server

I know there is much questions about json, but they don't answer my question (or I couldn't find anything, that would help me). Part of my Symfony2 controller that sends me data.

return $this->createResponse(array(
            'result' => $users
    ));
die();
}
/**
 * Interni pomocna funkce na vytvareni json odpovedi
 * @param unknown $array
 * @return \Symfony\Component\HttpFoundation\Response
 */
protected function createResponse($array = array()) {
return new Response(
        json_encode($array),
        200,
        array(
                        header('Content-type: application/json')    
        )
);
}

Javascript function that gets JSON data.

function getUsers(date_from, date_to) {
alert(date_from+" "+date_to);
var url = "{{ path('vetkomdochazkaBundle_apiGetUsers') }}";
$.post(url, JSON.stringify([date_from,date_to]), function(data) {
           markUsers(data['result']);
            }, 'json');
};

Everything works fine on localhost (wamp server), I gets data and parse it so I can use it as array. But when I run it on php5.3 server I get right data (I can write it with JSON.stringify), but I can't use them same way as on localhost (I can't use alert(data['result']), it only write object Object.

What am I doing wrong?

检查您的PHP版本JSON功能是否为PHP 5> = 5.2.0,

Symfony has a JsonResponse object that might make your code a little cleaner, and could fix your problem. Also, take out the die

/**
 * Interni pomocna funkce na vytvareni json odpovedi
 * @param unknown $array
 * @return \Symfony\Component\HttpFoundation\JsonResponse
 */
protected function createResponse($array = array()) {
    return new JsonResponse(
        $array,
        200
    );
}

otherwise, you need to set headers, like so

return new Response(
    json_encode($array),
    200,
    array('Content-type', 'application/json')
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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