At the end of the year, the project team will hold an anniversary activity, which requires a small GAME of HTML5. Since I have written cocos2D-X, I plan to make a small game of webpage with JS version, but I encountered the classic cross-domain problem of Ajax. And try out some weird tricks.
Ajax cross-domain
Cross-domain is nothing more than the following cases, because of security issues, browsers do not allow JS cross-domain access.
URL | The results of | why |
---|---|---|
a.b.com/image.png | successful | |
a.b.com/res/a.png | successful | |
a.b.com/res/b.png | failure | Agreement is different |
a.b.com:8080/res/b.png | failure | Different ports |
g.b.com/res/c.png | failure | Different host names |
The solution
Server forwarding
Since cross-domain access is not possible, you can use your own server as a springboard to access your own server and then forward to the target resource.
Configure cross-domain support
HTTP headers returned by servers that configure cross-domain resources:
Access-control-allow-origin: [your domain name] or wildcard * allows any domain, cross-domain Access.
- Images in CDN, such as seven Cows, public data, the default is to support cross-domain
- Self-built static file server, you need to query, how to configure
http header
header( 'Access-Control-Allow-Origin: *');
Qi Yin stunt
First write a tag on the page, download the image, after downloading the hidden, and then read in cocos2D-js.
<img src="http://172.17.132.113:8081/image_pack.png" onload="load(this)"/><script type="text/javascript">function load(image) {console.log("image load finish");image.style.display = "none";}Var res = (" http://172.17.132.113:8081/image_pack.plist ", "http://172.17.132.113:8081//image_pack.png");cc.loader.load(res, function () {cc.spriteFrameCache.addSpriteFrames(res[0], res[1]);that.initScene();});</script>