Skip to content

Instantly share code, notes, and snippets.

@auchomage
Last active May 12, 2016 17:18
Show Gist options
  • Save auchomage/c740a04e59ef7886ce3667306876f4ea to your computer and use it in GitHub Desktop.
Save auchomage/c740a04e59ef7886ce3667306876f4ea to your computer and use it in GitHub Desktop.
Problem ajax script: I can get data from an external file (cross site request), but when I try to convert it into javascript I keep getting an error.
{
"firstName": "Henry",
"lastName": "Lawson",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Practice CORS1</title>
</head>
<body>
<p>Consolidating my knowledge.</p>
<div id="output">Nothing yet.</div>
<script src="practiceCORS1.js"></script>
</body>
</html>
/**
* Created by ocj on 12/05/16.
*/
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
xhr.setRequestHeader('content-type','application/json');
} else {
xhr = null;
}
return xhr;
}
var request = createCORSRequest("get", "https://jsonblob.com/api/57339ef2e4b01190df64bd8f");
if (request){
request.onload = function(){
//do something with request.responseText
var respText = request.responseText;
console.log("*!* Data type : *!*", typeof respText );
console.log(respText);
// convertTexttoJavaScript
//var jScript = JSON.parse(respText); // ** Error is: practiceCORS1.html:13 Uncaught SyntaxError:
//Unexpected token < in JSON at position 16
//console.log("!** jScript **! :", jScript);
};
request.send(null);
}
@auchomage
Copy link
Author

The script seems to fail, whenever I try to convert the JSON string into javascript.
The error message is:

practiceCORS1.html:13 Uncaught SyntaxError:Unexpected token < in JSON at position 16

I don't understand why? I've specified the 'setRequestHeader' to be 'application/json'. Yet this was done in the example. I'm stumped.
I read an article (one of several), but this one seemed to be the most easily understood by myself. Here is the link
https://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/

@auchomage
Copy link
Author

auchomage commented May 12, 2016

I changed practiceCORS1.JS: LINE 16:

from:
var request = createCORSRequest("get", "https://jsonblob.com/57339ef2e4b01190df64bd8f");

to:
var request = createCORSRequest("get", "https://jsonblob.com/api/57339ef2e4b01190df64bd8f");

ie I added '/api' after the domain name
This made the difference and it now works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment