2017-10-18 66 views
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响应得到结果变量。

回答

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. 

一旦这种变化是由

+0

谢谢Onome矿亚当斯应该正常工作。在做出更正后,您选定了位置。我的代码工作正常。 –

相关问题