我们在做一个项目时需要把服务器的网页代码保存到本地节省流量,而里面的数据在服务器使用ajax来获取的,当我们把这个网页用本地wenview打开时,在ajax使用时会报
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help, check http://example.ex.com.
core.min.js:36 XMLHttpRequest cannot load http://【地址】. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://example.ex.com is therefore not allowed access.
查了好多资料有两个解决方案,
1:ajax上使用jsonp 但是必须使用get请求
类似这样

  $.ajax(url, {        data: {          'cityname': '襄阳',          'dtype': 'jsonp',          'key': 'xxxx',          '_': new Date().getTime()        },        dataType: 'jsonp',        crossDomain: true,        success: function(data) {          if(data && data.resultcode == '200'){            console.log(data.result.today);          }        }      });

但是我们这样肯定是不可以的 jsonp使用的数据必须含有callback,当我们按json解析时就会出错,必须让服务器返回jsonp格式的数据
2另一种方法 在android中使用
首先android,访问android WebView private 对象 WebViewCore mWebViewCore,调用 mWebViewCore的private 方法nativeRegisterURLSchemeAsLocal,把http和https忽悠成本地访问。 XMLHttpRequest即可自由跨域。
放代码

try {            if (Build.VERSION.SDK_INT >= 16) {                Class<?> clazz = webView.getSettings().getClass();                Method method = clazz.getMethod(                        "setAllowUniversalAccessFromFileURLs", boolean.class);                if (method != null) {                    method.invoke(webView.getSettings(), true);                }            }        } catch (IllegalArgumentException e) {            e.printStackTrace();        } catch (NoSuchMethodException e) {            e.printStackTrace();        } catch (IllegalAccessException e) {            e.printStackTrace();        } catch (InvocationTargetException e) {            e.printStackTrace();        }

把代码放在loadurl前 就可以自由的跨域访问啦

更多相关文章

  1. [置顶] Android实现RecyclerView的下拉刷新和上拉加载更多
  2. Content Provider 用法
  3. android SQLite3常用命令&语法
  4. Android中SQLite学习小结
  5. Android(安卓)Loader(二) CursorLoader
  6. Android(安卓)数据存储之SharedPreferences的使用
  7. Android(安卓)访问本地 HTML
  8. 转:Parcle
  9. android 访问移动网络时的wap代理设置

随机推荐

  1. Android(安卓)Wifi模块分析(一)
  2. android播放网络音频
  3. 在Android中解析ls 命令得到目录列表的方
  4. android下大文件分割上传
  5. android 单元测试cmd 命令集
  6. 【Android】Navigation初试-官方demo分析
  7. 如何将android(gingerbread)源码导入eclips
  8. activity启动模式
  9. Eclipse中导入Android工程
  10. [android]控件EditText常用属性