let quotesData; function getQuotes(){ return $.ajax({ headers:{ Accept:"application/json" }, url:'https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json', success: function(jsonQuotes){ if(typeof jsonQuotes==="string"){ quotesData = JSON.parse(jsonQuotes); console.log('quotesData'); console.log(quotesData); } } }) } getQuotes()
I was trying to complete project on fcc.Didn’t know how to add quotes in html.Looked up in their premade project found this piece.Can someone explain what is going on in this code?
Advertisement
Answer
It’s a hack to get around an incorrect Content-Type.
gist.githubusercontent.com
isn’t designed to host JSON data. It serves up plain text documents.
The success function tests to response to see if jQuery parsed it from JSON (which it will do if the Content-Type
response header says it is) and if the response is a string it assumes it is unparsed JSON.
This is risky. A valid JSON text might encode only a single string (and trying to double parse it will error) and the document might not be JSON in the first place (which would also cause an error).
A better solution would be to use an appropriate hosting service.