0
當我嘗試使用JSON.parse我得到這個錯誤解析reponseText:未捕獲的SyntaxError:意外的標記<在JSON在位置0在JSON.parse
Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse() at XMLHttpRequest.xhr.onreadystatechange (index.js:75)
任我運行下面的代碼。
的JavaScript/AJAX代碼
function calculateMeasurements() {
clearResult();
clearErrors();
var form = document.getElementById("measurement-form");
var action = form.getAttribute("action");
// gather form data
var form_data = new FormData(form);
for ([key, value] of form_data.entries()) {
console.log(key + ': ' + value);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', action, true);
// do not set content-type with FormData
//xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
var json = JSON.parse(result);
if (json.hasOwnProperty('errors') && json.errors.length > 0) {
displayErrors(form, json.errors);
} else {
postResult(json.volume);
}
}
};
xhr.send(form_data);
}
var button = document.getElementById("ajax-submit");
button.addEventListener("click", calculateMeasurements);
})();
process.php
<?php
function is_ajax_request(){
return $_SERVER["HTTP_X_REQUESTED_WITH"] && $_SERVER["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest";
}
$length = isset($_POST['length']) ? (int) $_POST['length'] : '';
$width = isset($_POST['width']) ? (int) $_POST['width'] : '';
$height = isset($_POST['height']) ? (int) $_POST['height'] : '';
$errors = [];
if(empty($length)){$errors[] = "length";}
if(empty($width)){$errors[] = "width";}
if(empty($height)){$errors[] = "height";}
if(!empty($errors)){
$result_array = array('errors' => $errors);
echo json.encode($result_array);
exit;
}
$volume = $length * $width * $height;
if(is_ajax_request()) {
echo json.encode(array('volume' => $volume));
} else {
exit;
}
?>
我注意到這個錯誤隨時我使用JSON.parse從Ajax響應得到結果變量。
謝謝Onome礦亞當斯應該正常工作。在做出更正後,您選定了位置。我的代碼工作正常。 –