从Jquery发送到PHP时格式错误的JSON

时间:2016-07-07 17:27:02

标签: javascript php jquery json ajax

我试图将JQuery请求发送到我正在制作的API(第一次学习!)但是我的php代码报告JSON格式不正确。

如果我在PHP中创建一个JSON数组并通过它可以正常工作,但如果我尝试通过JQuery请求它总是说不正确。

我卡住了!

Javascript方面看起来像这样......

jsonrequest = "{request: 'getJobs', token : 'eb024fab2bf6a1bfb5863dcaabcfd63fcaea50e429237df3f1cbcbfcf9b2'}";
    $.ajax({
    url: 'api.php',
    async: true,
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    data: jsonrequest,


       success: function ( result ) {
            console.log(result);
        }
});

,PHP看起来像这样

$data       = file_get_contents("php://input");

if(isJson($data)) {

        // never passes the isJSON validation.

        $json       = json_decode($data,true);
        $request    = sanitize($json['request']);
        }


function isJSON($string)
{
    // decode the JSON data
    $result = json_decode($string);

    // switch and check possible JSON errors
    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            $error = ''; // JSON is valid // No error has occurred
            break;
        case JSON_ERROR_DEPTH:
            $error = 'The maximum stack depth has been exceeded.';
            break;
        case JSON_ERROR_STATE_MISMATCH:
            $error = 'Invalid or malformed JSON.';
            break;
        case JSON_ERROR_CTRL_CHAR:
            $error = 'Control character error, possibly incorrectly encoded.';
            break;
        case JSON_ERROR_SYNTAX:
            $error = 'Syntax error, malformed JSON.';
            break;
        // PHP >= 5.3.3
        case JSON_ERROR_UTF8:
            $error = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
            break;
        // PHP >= 5.5.0
        case JSON_ERROR_RECURSION:
            $error = 'One or more recursive references in the value to be encoded.';
            break;
        // PHP >= 5.5.0
        case JSON_ERROR_INF_OR_NAN:
            $error = 'One or more NAN or INF values in the value to be encoded.';
            break;
        case JSON_ERROR_UNSUPPORTED_TYPE:
            $error = 'A value of a type that cannot be encoded was given.';
            break;
        default:
            $error = 'Unknown JSON error occured.';
            break;
    }

    if ($error !== '') {
        // throw the Exception or exit // or whatever :)
        $output = array('status' => "error",'message' => $error);
        echo json_encode($output);
        exit;
    }

    // everything is OK
    return $result;
}

2 个答案:

答案 0 :(得分:2)

尝试

data: {request: 'getJobs', token: 'eb024fab2bf6a1bfb5863dcaabcfd63fcaea50e429237df3f1cbcbfcf9b2'}

没有引号。 jQuery应该为你处理。

如果它仍然失败,可以在开发人员工具中打开它,查看ajax请求,看看数据实际看起来是什么样的想法。

答案 1 :(得分:1)

您的代码

jsonrequest = "{request: 'getJobs', token : 'eb024fab2bf6a1bfb5863dcaabcfd63fcaea50e429237df3f1cbcbfcf9b2'}";

您将jsonrequest定义为字符串而不是对象。

尝试以下两种方法之一(注意,键名也必须用引号括起来)

 jsonrequest = {'request': 'getJobs', 'token' : 'eb024fab2bf6a1bfb5863dcaabcfd63fcaea50e429237df3f1cbcbfcf9b2'};

或者如果jsonrequest必须构建为字符串,则可以使用jQuery.parseJSON()

jsonrequest = '{"request": "getJobs", "token" : "eb024fab2bf6a1bfb5863dcaabcfd63fcaea50e429237df3f1cbcbfcf9b2"}';
jsonrequest = $.parseJSON(jsonrequest);