【问题解决】XMLHttpRequest cannot load http://xxx.xxx No 'Access-Control-Allow-Origin'

问题描述:"XMLHttpRequest cannot load http://xxx.xxx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access."/xxx.html (0)

出现原因:ajax本身实际上是通过XMLHttpRequest对象来进行数据的交互,而浏览器处于安全考虑,不允许js代码进行跨域操作,所以会出现这个错误

解决方法:

方案一.一般jQuery解决跨域是通过jsonp的方式,添加callback=xxx,服务器返回xxx(...),这种方式需要服务器代码帮忙

举个栗子:在index.html中 



	
		
		
		
		
	
	
		



jsonp.php

最终index.html中显示 3 

方案二.通过CORS(跨域资源共享) Proxy 对请求进行转发,就可以实现跨域访问。

如: 请求地址是 http://op.juhe.cn/onebox/weather/query?key=3611a1e75f91ff1544fc9f84ec489021&dtype=json&cityname=武汉

则修改为  跨域服务器地址/ http://op.juhe.cn/onebox/weather/query?key=3611a1e75f91ff1544fc9f84ec489021&dtype=json&cityname=武汉

(例如:http://proxy.e12e.com/? http://op.juhe.cn/onebox/weather/query?key=3611a1e75f91ff1544fc9f84ec489021&dtype=json&cityname=武汉)这样就可以很方便使用代理的方式来访问api接口了

你可能感兴趣的:(问题解决,前端,xmlhttprequest,jquery,javascript)