私は(初めて学習している)APIにJQueryリクエストを送信しようとしていますが、私のPHPコードでJSONが不正です。JqueryからPHPへの送信時にJSON形式が正しくない
PHPでJSON配列を作成して渡すとうまくいきますが、JQuery経由でリクエストしようとすると、常に不正な形式になります。
Im Stuck! 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;
}
JSONにはオブジェクトキーの引用符も必要です。 –