无法通过AJAX从PHP返回数据

时间:2015-02-27 11:01:16

标签: php jquery ajax

我正在尝试通过AJAX(使用Chrome)从PHP文件中的函数返回数据

JS:

    $.ajax({
            url: 'http://www.site.co.uk/api/file.php',
            data: data, 
            dataType: 'json', 
            type: 'POST', 
            contentType: 'application/json',
            async: false,
            success: function (jsonData){
                console.log("SUCCESS");
                var responseText = jQuery.parseJSON(jsonData.responseText);
                console.log(responseText);
            },
            error: function (jsonData){
                console.log("ERROR");
                var responseText = jQuery.parseJSON(jsonData.responseText);
                console.log(responseText);
            }
        });

PHP的相关部分:

public function post_method()
{
    $data['error_message'] = "Error message text";
    return json_encode($data);
}

在控制台中我得到了:

POST http://www.site.co.uk/api/file.php 500 (Internal Server Error)
ERROR
Object {status: "{", message: "{"}

在PHP中,如果我替换

return json_encode($data);

return $data;

控制台显示

SUCCESS
Uncaught SyntaxError: Unexpected token u jquery.js:3 

不确定为什么我不能得到'error_message',并且不确定为什么使用'json_encode'会产生500错误。

@Johannes Reuter - 这有点复杂,但我正在调用post_method():

public function route_method()
{
   switch($this->resource['request_method'])
    {
        case 'POST':
            return $this->post_method();
            break;
        default:
            return FALSE;
            break;                
    }

}

这是我没写过的一些api框架代码的一部分。 '$ this-> resource'基本上被传递给类构造函数。在其他PHP文件中成功使用相同的方法。

@Rory McCrossan - 我该如何定义它?我认为只需将其创建为数组即可。

3 个答案:

答案 0 :(得分:1)

如果您在请求中将dataType作为json通知,则不需要使用jQuery.parseJSON功能,因为它的 json

答案 1 :(得分:0)

你会试试。

echo json_encode($data);exit;

答案 2 :(得分:0)

使用echo json_encode($data);die;代替return json_encode($data);