惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Security Latest
Security Latest
C
Cisco Blogs
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
C
Cyber Attacks, Cyber Crime and Cyber Security
NISL@THU
NISL@THU
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
D
Docker
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
G
Google Developers Blog
Schneier on Security
Schneier on Security
小众软件
小众软件
爱范儿
爱范儿
GbyAI
GbyAI
J
Java Code Geeks
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
TaoSecurity Blog
TaoSecurity Blog
MyScale Blog
MyScale Blog
B
Blog RSS Feed
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Y
Y Combinator Blog
S
Schneier on Security
Latest news
Latest news
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 叶小钗
F
Fortinet All Blogs
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
V
V2EX
V2EX - 技术
V2EX - 技术
O
OpenAI News
W
WeLiveSecurity

Mathias Bynens

A horrifying globalThis polyfill in universal JavaScript JavaScript engine fundamentals: optimizing prototypes JavaScript engine fundamentals: Shapes and Inline Caches Asynchronous stack traces: why await beats Promise#then() ECMAScript regular expressions are getting better! Unicode property escapes in JavaScript regular expressions ES2015 const is not about immutability Valid JavaScript variable names in ES2015 Unicode-aware regular expressions in ES2015 Dear Google, please fix plain text emails in Gmail PBKDF2+HMAC hash collisions explained JavaScript has a Unicode problem Processing Content Security Policy violation reports Hiding JSON-formatted data in the DOM with CSP enabled Reserved keywords in JavaScript How to support full Unicode in MySQL databases How to speedrun Dropbox’s Dropquest 2012 Unquoted font family names in CSS Unquoted property names / object keys in JavaScript Valid JavaScript variable names in ES5 CSS character escape sequences JavaScript’s internal character encoding: UCS-2 or UTF-16? The smallest possible valid (X)HTML documents JavaScript character escape sequences JavaScript foo.prototype.bar notation Ambiguous ampersands HTML element + attribute notation How I detect and use localStorage: a simple JavaScript pattern Unquoted attribute values in HTML and CSS/JS selectors The end-tag open (ETAGO) delimiter Using the oninput event handler with onkeyup/onkeydown as its fallback Everything you always wanted to know about touch icons In defense of CSS hacks — introducing “safe CSS hacks” AirPlay video support in iOS Safari — a bookmarklet Completing Dropbox’s Dropquest 2011 in 60 seconds Using CSS without HTML How to create simple Mac apps from shell scripts Using setTimeout to speed up window.onload Bulletproof JavaScript benchmarks Thoughts on Safari Reader’s generated HTML How to enable Safari Reader on your site? The XML serialization of HTML5, aka ‘XHTML5’ The id attribute got more classy in HTML5 The three levels of HTML5 usage The HTML5 document.head DOM tree accessor Bulletproof HTML5 <details> fallback using jQuery Displaying hidden elements like <head> using CSS Inline <script> and <style> vs. external .js and .css — what’s the size threshold? Using Showdown/PageDown with and without jQuery
Loading JSON-formatted data with Ajax and xhr.responseType='json'
Mathias · 2013-07-24 · via Mathias Bynens

This post explains a hidden gem in the XMLHttpRequest standard that simplifies the process of fetching and parsing JSON data through Ajax.

JSON & JSON-P

A common way to offer server-generated data to browsers so that it can be used in client-side JavaScript is by formatting the data as JSON, and making it accessible through its own URL. For example:

$ curl 'https://mathiasbynens.be/demo/ip'
{"ip":"173.194.65.100"}

To make it easy to use this data in client-side JavaScript, most API endpoints offer a JSON-P version too:

$ curl 'https://mathiasbynens.be/demo/ip?callback=foo'
foo({"ip":"173.194.65.100"})

JSON-P allows you to use JSON-formatted data directly in JavaScript without having to programmatically parse it first. In other words, JSON-P is valid JavaScript, which allows you to do:

<script>
	window.hollaback = function(data) {
		alert('Your public IP address is: ' + data.ip);
	};
</script>
<script src="https://mathiasbynens.be/demo/ip?callback=hollaback"></script>

Some APIs don’t offer JSON-P, though, and in some situations it’s preferable to load the raw JSON data through Ajax, then parse the serialized data string using JSON.parse() (or its polyfill for older browsers). This can be done as follows:

var getJSON = function(url, successHandler, errorHandler) {
	var xhr = typeof XMLHttpRequest != 'undefined'
		? new XMLHttpRequest()
		: new ActiveXObject('Microsoft.XMLHTTP');
	xhr.open('get', url, true);
	xhr.onreadystatechange = function() {
		var status;
		var data;
		// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
		if (xhr.readyState == 4) { // `DONE`
			status = xhr.status;
			if (status == 200) {
				data = JSON.parse(xhr.responseText);
				successHandler && successHandler(data);
			} else {
				errorHandler && errorHandler(status);
			}
		}
	};
	xhr.send();
};

getJSON('https://mathiasbynens.be/demo/ip', function(data) {
	alert('Your public IP address is: ' + data.ip);
}, function(status) {
	alert('Something went wrong.');
});

The above code works in pretty much any relevant browser, including IE6.

So far, I probably haven’t told you anything you didn’t already know. But here comes the good part. Thanks to a ‘hidden’ (not widely known) gem in the XMLHttpRequest standard, this code can be simplified a bit!

Enter xhr.responseType = 'json'

Each XMLHttpRequest instance has a responseType property which can be set to indicate the expected response type. When the property is set to the string 'json', browsers that support this feature automatically handle the JSON.parse() step for you. Using this feature, the above example can be written more elegantly:

var getJSON = function(url, successHandler, errorHandler) {
	var xhr = typeof XMLHttpRequest != 'undefined'
		? new XMLHttpRequest()
		: new ActiveXObject('Microsoft.XMLHTTP');
	xhr.open('get', url, true);
	xhr.responseType = 'json';
	xhr.onreadystatechange = function() {
		var status;
		var data;
		// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
		if (xhr.readyState == 4) { // `DONE`
			status = xhr.status;
			if (status == 200) {
				successHandler && successHandler(xhr.response);
			} else {
				errorHandler && errorHandler(status);
			}
		}
	};
	xhr.send();
};

getJSON('https://mathiasbynens.be/demo/ip', function(data) {
	alert('Your public IP address is: ' + data.ip);
}, function(status) {
	alert('Something went wrong.');
});

Check out the demo. Note that when the responseType is set to 'json', xhr.response must be used instead of xhr.responseText. When the browser fails to parse the response as JSON, null is returned (instead of throwing an error).

Since this code only works in modern browsers with xhr.responseType = 'json' support anyway, we might as well get rid of the code paths for legacy browsers:

var getJSON = function(url, successHandler, errorHandler) {
	var xhr = new XMLHttpRequest();
	xhr.open('get', url, true);
	xhr.responseType = 'json';
	xhr.onload = function() {
		var status = xhr.status;
		if (status == 200) {
			successHandler && successHandler(xhr.response);
		} else {
			errorHandler && errorHandler(status);
		}
	};
	xhr.send();
};

getJSON('https://mathiasbynens.be/demo/ip', function(data) {
	alert('Your public IP address is: ' + data.ip);
}, function(status) {
	alert('Something went wrong.');
});

Much better, no? This is what the future looks like :) It gets even better when combined with JavaScript promises:

var getJSON = function(url) {
	return new Promise(function(resolve, reject) {
		var xhr = new XMLHttpRequest();
		xhr.open('get', url, true);
		xhr.responseType = 'json';
		xhr.onload = function() {
			var status = xhr.status;
			if (status == 200) {
				resolve(xhr.response);
			} else {
				reject(status);
			}
		};
		xhr.send();
	});
};

getJSON('https://mathiasbynens.be/demo/ip').then(function(data) {
	alert('Your public IP address is: ' + data.ip);
}, function(status) {
	alert('Something went wrong.');
});

Browser support

xhr.responseType = 'json' has only been in the spec since December 2011, and as of March 2016, Firefox ≥ 10 (Gecko), Chrome/Chromium ≥ 31, Opera (even the old Presto-based Opera 12!), Microsoft Edge, and Safari/WebKit all support it.