未捕获的SyntaxError:意外的令牌<在JSON位于JSON.parse的0位

时间:2017-10-18 04:25:55

标签: ajax

当我尝试使用JSON.parse解析reponseText时出现此错误:

  

未捕获的SyntaxError:意外的令牌<在JSON的0号位置   XMLHttpRequest.xhr.onreadystatechange中的JSON.parse()   (index.js:75)

任何时候我都运行以下代码。

javascript / ajax code

    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;
  }

?>

我在从ajax响应获取的结果变量上使用JSON.parse的时候注意到了这个错误。

1 个答案:

答案 0 :(得分:0)

我不认为他们的javascript代码有任何问题。请尝试正确使用PHP功能。它应该喜欢这个

echo json_encode(array('volume' => $volume)); 

echo json_encode($result_array);

AND NOT:

echo json.encode(array('volume' => $volume)); // json.encode as you have used in your code is wrong.

echo json.encode($result_array) // json.encode as you have used in your code is wrong.

一旦做出此更改,它应该可以正常工作