2013-01-19 14 views
5

Sto tentando di recuperare un feed JSON personalizzato che ho scritto con jQuery utilizzando il metodo getJSON. Per un motivo sconosciuto, l'URL sembra avere cache_gen.php?location=PL4 rimosso dalla fine e sostituito con [oggetto% 20Object] con conseguente errore 404.JSON Richiesta aggiunta con [oggetto% 20Object] in jQuery

Ecco il jQuery che sto utilizzando:

var fetchData = function() { 

    if (Modernizr.localstorage) { 

     var api_location = "http://weatherapp.dev/cache_gen.php"; 
     var user_location = "PL4"; 
     var date = new Date(); 

     console.log(api_location + '?location=' + user_location); 

     jQuery.getJSON({ 
      type: "GET", 
      url: api_location + '?location=' + user_location, 
      dataType: "json", 
      success: function(jsonData) { 
       console.log(jsonData); 
      } 
     }); 

    } else { 
     alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.'); 
    } 
} 

fetchData(); 

Dal log della console posso vedere la stringa URL viene calcolata correttamente come: http://weatherapp.dev/cache_gen.php?location=PL4

Tuttavia la seconda linea nella console è: Failed to load resource: the server responded with a status of 404 (Not Found).

Qualcuno può indicarmi la giusta direzione?

AGGIORNAMENTO 19/01/2013 23:15

Beh, ho appena convertito in modo che sia adatta perfettamente i documenti utilizzando $.ajax. Ho anche aggiunto un evento di errore e registrato tutti i dati che gli vengono passati.

var fetchData = function() { 

    if (Modernizr.localstorage) { 

     var api_location = "http://weatherapp.dev/cache_gen.php"; 
     var user_location = "PL4"; 
     var date = new Date(); 

     var url = api_location + '?location=' + user_location; 

     console.log(url); 

     jQuery.ajax({ 
      type: "GET", 
      url: api_location + '?location=' + user_location, 
      dataType: "json", 
      success: function(jsonData) { 

       console.log(jsonData); 
      }, 
      error: function(jqXHR, textStatus, errorThrown) { 
       console.log('textStatus: ' + textStatus); 
       console.log('errorThrown: ' + errorThrown); 
       console.log('jqXHR' + jqXHR); 
      } 
     }); 

    } else { 
     alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.'); 
    } 
} 

fetchData(); 

Dopo questa mia console mi dà le seguenti informazioni:

http://weatherapp.dev/cache_gen.php?location=PL4 
download_api.js:44textStatus: parsererror 
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string 
download_api.js:46jqXHR[object Object] 

ho assicurato le intestazioni per il feed JSON sono in corso, e l'alimentazione è sicuramente scontando JSON valido (memorizza nella cache in modo efficace un 3 ° feed servizio party per risparmiare costi sull'API).

+0

http://weatherapp.dev/cache_gen.php?location=PL4 non è un URL di lavoro.<----- cliccalo – Popnoodles

+0

@popnoodles, potrebbe essere un reindirizzamento '/ etc/hosts :). Ma certamente '.dev' sembra fishy – Alexander

+0

.dev è un dominio di sviluppo. È stato impostato un host virtuale Apache sul mio sistema locale, che ha una voce nel mio '' '/ etc/hosts''' per assicurarmi che sia risolto correttamente. Posso accedere a questo dominio nel mio browser, è lo stesso dominio di dove viene caricato il file JS. –

risposta

5

Il motivo per cui si vede questo errore:

http://weatherapp.dev/cache_gen.php?location=PL4 
download_api.js:44textStatus: parsererror 
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string 
download_api.js:46jqXHR[object Object] 

è perché il vostro JSON non è valido. Anche se una risposta ritorna dal server correttamente, se dataType è "json" e la risposta restituita non è formattata correttamente JSON, jQuery eseguirà il parametro della funzione di errore.

http://jsonlint.com è un modo molto semplice e veloce per verificare la validità della stringa JSON.

+0

Grazie ancora Adam. –

+0

Estendere la buona risposta di @ Adam. Più in generale, qualcosa non corrisponde tra il valore "datatype" della chiamata (esplicito o implicito) e i dati effettivi restituiti dal server. Stavo specificando "html" come mio tipo di dati e ho ricevuto questo errore. Ho omesso il parametro datatype opzionale e ho smesso di vedere l'errore. Sto sicuramente restituendo html e inserendo nella pagina, ma sono disposto a inchinarmi alla dea ajax e lasciare che pensi che il mio valore di ritorno è qualsiasi tipo che vuole finché la mia chiamata funziona. –

0

Partenza il reale uso della funzione:

http://api.jquery.com/jQuery.getJSON/

Non è possibile passare al parametro oggetto in $.getJSON come con $.ajax, il codice dovrebbe essere simile a questo:

jQuery.getJSON('api_location + '?location=' + user_location) 
     .done(function() { 
      //success here 
     }) 
     .fail(function() { 
      //fail here 
     }); 

a forse rendilo un po 'più chiaro, $.getJSON è solo una "funzione wrapper" che alla fine chiama $.ajax con {type:'get',dataType:'JSON'}. Puoi vedere questo nel link che ho fornito sopra.

+0

In realtà solo più facile per l'OP sostituire .getJSON con .ajax – Popnoodles

+0

@popnoodles perché? OP che non usa nessuna opzione che $ $ .getJSON' non includa già – charlietfl

+1

@charlietfl perché hanno scritto il loro codice come se avessero dovuto usare .ajax - cambiare solo 7 caratteri è più facile. – Popnoodles

0

Mi sono imbattuto nello stesso problema oggi. Nel mio caso stavo assegnando un oggetto JSON a una variabile denominata 'location', che è una parola riservata in JavaScript under Windows e apparentemente è una scorciatoia per windows.location! Quindi il browser reindirizzato all'URL corrente con [oggetto% 20Object] è stato aggiunto ad esso. Semplice usa un nome di variabile diverso da "posizione" se la stessa cosa ti succede. Spero che questo aiuti qualcuno.