2015-04-20 13 views
8

Ho usato Laravel Response :: json per generare una risposta JSON.SyntaxError: JSON.parse: carattere imprevisto nella riga 1 colonna 2 dei dati JSON - FireBug segnala questo errore. Qualche soluzione?

return Response::json(array('subjects' => $subjects, 'year' => $year, 'sem' => $sem)); 

Quando si esegue la richiesta, ottengo un JSON valido (testato in JSONLint) come risposta.

Ma il seguente metodo di jQuery non riesce: $.parseJSON(data)

ottengo il seguente errore nel FireBug:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

La risposta ricevo:

{ 
    "subjects": [ 
     { 
      "id": 1, 
      "name": "Control Systems", 
      "semester": 1, 
      "year": 3, 
      "branch_id": 4 
     }, 
     { 
      "id": 2, 
      "name": "Analog Communications", 
      "semester": 1, 
      "year": 3, 
      "branch_id": 4 
     }, 
     { 
      "id": 3, 
      "name": "Linear IC Applications", 
      "semester": 1, 
      "year": 3, 
      "branch_id": 4 
     }, 
     { 
      "id": 4, 
      "name": "Antennas & Wave Propagation", 
      "semester": 1, 
      "year": 3, 
      "branch_id": 4 
     } 
    ], 
    "year": 3, 
    "sem": 2 
} 

E il codice dove sono cercando di analizzarlo:

$(document).ready(function() { 
    $('#branchAndSubjects').click(function() { 
     $.post('/findBranchAndSubjects', { 
      roll: roll, 
      _token: "{{csrf_token()}}" 
     }, function(data) { 
      var subjects = $.parseJSON(data); 
     }); 
    }); 
}); 

risposta

19

Se stai facendo il $.parseJSON(data) in un gestore di successo ajax Dal momento che si sta facendo il $.parseJSON(data) in un gestore di successo ajax, il problema è quasi certamente che jQuery ha già analizzato per voi. jQuery guarderà il Content-Type della risposta e, se è application/json, lo analizzerà e fornirà il risultato analizzato al gestore di successo. La prima cosa che accadrà se la passerai a $.parseJSON sarà che verrà convertita in una stringa ("[object Object]", nel tuo caso), che quindi non sarà possibile analizzare da $.parseJSON.

Basta usare data come-si, è già un oggetto, grazie alla analisi automatica:

$(document).ready(function() { 
    $('#branchAndSubjects').click(function() { 
     $.post('/findBranchAndSubjects', { 
      roll: roll, 
      _token: "{{csrf_token()}}" 
     }, function(data) { 
      console.log(data.year);    // 3 
      console.log(data.subjects.length); // 4 
      console.log(data.subjects[0].name); // Control Systems 
     }); 
    }); 
}); 
+2

@ t-j-Crowder Grazie mille! Lavorare come dovrebbe Indovina che il JSON è stato analizzato già. Grazie ancora! –

Problemi correlati