|
| 1 | +--- |
| 2 | +author: shellbye |
| 3 | +comments: true |
| 4 | +date: 2015-12-27 11:27:08+00:00 |
| 5 | +layout: post |
| 6 | +slug: pure-js-implements-getJSON-with-header-X-Requested-With |
| 7 | +title: Pure js implements getJSON with X-Requested-With header |
| 8 | +categories: |
| 9 | +- tech_world |
| 10 | +tags: |
| 11 | +- javascript |
| 12 | +- js |
| 13 | +- jquery |
| 14 | +- http |
| 15 | +--- |
| 16 | + |
| 17 | +用纯js实现jquery里面的getJSON方法在网上是有比较多的资料的, |
| 18 | +比如在[You Might Not Need Jquery]中,就有如下实现: |
| 19 | + |
| 20 | +{% highlight javascript %} |
| 21 | +// jquery |
| 22 | +$.getJSON('/my/url', function(data) { |
| 23 | + |
| 24 | +}); |
| 25 | + |
| 26 | +// pure js |
| 27 | +var request = new XMLHttpRequest(); |
| 28 | +request.open('GET', '/my/url', true); |
| 29 | + |
| 30 | +request.onload = function() { |
| 31 | + if (this.status >= 200 && this.status < 400) { |
| 32 | + // Success! |
| 33 | + var data = JSON.parse(this.response); |
| 34 | + } else { |
| 35 | + // We reached our target server, but it returned an error |
| 36 | + |
| 37 | + } |
| 38 | +}; |
| 39 | + |
| 40 | +request.onerror = function() { |
| 41 | + // There was a connection error of some sort |
| 42 | +}; |
| 43 | + |
| 44 | +request.send(); |
| 45 | +{% endhighlight %} |
| 46 | + |
| 47 | +但是我在用这段代码异步获取验证码图片时,其效果却和```getJSON```不一样, |
| 48 | +用后者时是可以正常返回结果的,但是用纯js时,后台却返回了404, |
| 49 | +对比两次的HTTP请求之后,发现用纯js方法时构造的HTTP请求比用```getJSON```少了一个Header, |
| 50 | +就是```X-Requested-With```,这是一个很重要的非标准Header, |
| 51 | +[Wiki]解释的比较清楚了, |
| 52 | + |
| 53 | +> mainly used to identify Ajax requests. |
| 54 | +Most JavaScript frameworks send this field with value of ```XMLHttpRequest``` |
| 55 | + |
| 56 | +也就是说这个Header是用来标记请求是否为```Ajax```的,为什么要这样做呢? |
| 57 | +为了防止跨站脚本攻击,也就是大名鼎鼎的```CSRF```,那么既然如此,需要怎么做呢? |
| 58 | +很简单,就是在上面的代码```open```之后添加如下一行即可: |
| 59 | + |
| 60 | +{% highlight javascript %} |
| 61 | +request.setRequestHeader("X-Requested-With", "XMLHttpRequest"); |
| 62 | +{% endhighlight %} |
| 63 | + |
| 64 | +[You Might Not Need Jquery]:http://youmightnotneedjquery.com/#json |
| 65 | +[Wiki]:https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Common_non-standard_request_fields |
0 commit comments