2017-05-18 11 views
0

JSONコードをサーバーから返そうとしているので、JavaScript内で操作できます。Vanilla ES6 aJax call予期しないトークン

しかし、私は次のエラーを取得しています:ここで

Uncaught SyntaxError: Unexpected token m in JSON at position 10

は私のコードです:

getJSON(url, success) { 
     let query = [ 'cars', 'vans', 'bikes' ]; 

     var xhr = new XMLHttpRequest(); 
     xhr.onreadystatechange = function() { 
     if (xhr.readyState === 4) { 
      if (xhr.status === 200) { 
      success(JSON.parse(xhr.responseText)); 
      } else { 
      exit(xhr.responseText); 
      } 
     } 
     }; 
     xhr.open('GET', url); 
     xhr.send(); 
    } 

これは、私はちょうどxhr.responseTextをCONSOLE.LOG場合、私が得る応答である:

[ 
    { 
    make: 'VOLVO' 
    }, 
    { 
    make: 'AUDI' 
    }, 
    { 
    make: 'VOLKSWAGON' 
    }, 
] 
+6

これは有効なJSONではありません。 JSONは末尾にカンマを持つことはできず、プロパティ名と文字列には常に二重引用符が必要です。 – nils

+0

クラップ、私の間違い。私はJSONを台無しにしました –

+2

サーバーが無効なデータを返すときに正常に失敗するために、エラーをキャッチしたいかもしれません。 –

答えて

1

解析しようとしているオブジェクトは有効なJavaScriptオブジェクトですが、有効なJSONはありません。

key sがあなたが任意の末尾のコンマを使用しないでください

a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes

のように定義された文字列、(Can you use a trailing comma in a JSON object?を参照)でなければなりません。あなたのオブジェクトの

適切なJSON文字列は次のようになります。

let s = '[ {"make": "VOLVO"}, {"make": "AUDI"}, {"make": "VOLKSWAGON"} ]'; 

コードは、この問題を検出するために固定することができます

getJSON(url, success) { 
    let query = [ 'cars', 'vans', 'bikes' ]; 
    let xhr = new XMLHttpRequest(); 

    xhr.onreadystatechange = function() { 
     if (xhr.readyState === 4) { 
      if (xhr.status === 200) { 
       try { 
        let parsedJSON = JSON.parse(xhr.responseText); 
        success(parsedJSON); 
       } catch (e) { 
        if (e instanceof SyntaxError === true) { 
         // Problem with the format of the JSON string. 
        } else { 
         // Other error 
        } 
       } 
      } else { 
       exit(xhr.responseText); 
      } 
     } 
    }; 

    xhr.open('GET', url); 
    xhr.send(); 
} 

その他を。リソース:

関連する問題