JSONP is a technique to get data from server without cross-domain issues.
JSONP does not use the XMLHttpRequest, instead it uses <script> tag.
window.onload = function() {
var s = document.createElement("script");
s.src = "https://www.w3schools.com/js/demo_jsonp.php";
document.write(s.outerHTML);
};
// This function will run after the content is fully loaded from the server
function myFunc(myObj) {
document.write(myObj.name + " is " + myObj.age + " and he lives in " + myObj.city);
}
Requesting a content from another domain can cause problems, due to cross-domain policy. <script> tag does not have this problem and that is the reason why it uses the tag instead of using XMLHttpRequest object.
...
Content of the remote demo_jsonp.php filemyFunc({"name":"John", "age":30, "city":"New York"});var myObj, i, j, x = "";
myObj = {
"name":"John",
"age":30,
"cars": [
{"name":"Ford", "models":["Fiesta", "Focus", "Mustang"]},
{"name":"BMW", "models":["320", "X3", "X5"]},
{"name":"Fiat", "models":["500", "Panda"] }
]
}
To access nested JSON arraysfor (i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}string, number, object, array, boolean or null
...
In JavaScript:
Array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, undefined, symbolvar myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
// Accessing nested object properties
document.write(myObj.cars.car2);
document.write("<br />");
document.write(myObj.cars["car2"]);
document.write("<br />");
document.write(myObj["cars"]["car2"]);JSON.stringify() will remove functions from a JavaScript object because function is not valid data type in JSON var obj = { name: "John", age: function () {return 30;}, city: "New York" };
// Functions and any other unsupported data types will be ignored
var myJSON = JSON.stringify(obj);
document.write(myJSON);The result will be:{"name":"John","city":"New York"}
As we can see, the function is removed. To solve this issue we can convert the function into string before running stringify var obj = { name: "John", age: function () {return 30;}, city: "New York" };
obj.age = obj.age.toString();
var myJSON = JSON.stringify(obj);
document.write(myJSON);The result will be:{"name":"John","age":"function () {return 30;}","city":"New York"}var text = '{ "name":"John", "age":"function () {return 30;}", "city":"New York"}';
var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age();var text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.write(obj.name + ", " + obj.birth)
Also we can use the second parameter of the JSON.parse() function, called reviver that checks each property, before returning the valuevar text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});
document.write(obj.name + ", " + obj.birth)derived from an array, the method will return a JavaScript array, instead of an objectvar xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myArr[0];
}
};
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();derived from an object) from the server by using an XMLHttpRequest request
As long as the response from the server is written in JSON format, we can parse the JSON data into a JavaScript objectvar xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();{ "name": "John" }In JavaScript we can have names without quotes:{ name: "John" }
In JavaScript, keys can be strings, numbers, or identifier names:{ 12: "John" }
In JSON, values must be one of the following data types:- a string
- a number
- an object (JSON object)
- an array
- a boolean
- nullIn JavaScript, values can be all of the above listed types, plus any other valid JavaScript expression, including:- a function
- a date
- a symbol
- undefined
In JSON, string values must be written with double quotes:{ "name":"John" }In JavaScript, we can write string values with double or single quotes:{ name: 'John' }