2017-10-18 4 views
0

の位置0でJSONに予期しないトークン<私はこのエラーを取得するJSON.parseを使用してreponseTextを解析しようとします。キャッチされないでSyntaxError:</p> <blockquote> <p>Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse() at XMLHttpRequest.xhr.onreadystatechange (index.js:75)</p> </blockquote> <p>私は以下のコードを実行する任意の時間を:JSON.parse

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

?> 

私は、AJAX応答から得た結果を変数にJSON.parseを使用して、このエラーをいつでも気づきました。

答えて

0

あなたのjavascriptコードに何か問題があるとは思わない。 php関数を正しく使ってみてください。この変更は

+0

おかげOnomeマインアダムス行われた後、それが正常に動作するはず

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. 

:それはこの

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

AND NOTが好きなはずです。あなたが座った訂正をした後。私のコードは正常に動作しています。 –

関連する問題