Android與Javascript交互JSON對象

webview.loadUrl(“JavaScript:”+callbackFunction+”(‘”+data+”’)”); 這種方式將jsonobject類型的data傳給js,因爲js那邊得到就是一個string的對象。


與此同時,js主動調用android的對象方式,android也無法返回給js一個jsonobject,需要js做一下轉換,例如:


Android 代碼:

  1. WebView mWebView = (WebView) this.findViewById(R.id.webview);  
  2. WebSettings settings = mWebView.getSettings();  
  3. settings.setJavaScriptEnabled(true);  
  4. settings.setPluginsEnabled(true);  
  5. settings.setAllowFileAccess(true);  
  6.   
  7. settings.setCacheMode(WebSettings.LOAD_NO_CACHE);  
  8. mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);//不加上,會顯示白邊  
  9. String  url=”file:///android_asset/t.html”; //js代碼卸載t.html裏  
  10. NavigationInstance navigation =new NavigationInstance(this);  
  11. mWebView.addJavascriptInterface(navigation, ”Navigation”);  
WebView mWebView = (WebView) this.findViewById(R.id.webview);
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setPluginsEnabled(true);
settings.setAllowFileAccess(true);

settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);//不加上,會顯示白邊
String  url="file:///android_asset/t.html"; //js代碼卸載t.html裏
NavigationInstance navigation =new NavigationInstance(this);
mWebView.addJavascriptInterface(navigation, "Navigation");



NavigationInstance裏的代碼:

  1. @Override  
  2. public JSONObject GetManeuverInfo() {  
  3. try{  
  4. JSONObject test=new JSONObject();  
  5. test.put(”maomao”“value”);  
  6. return test;  
  7. //return new JSONObject(bean.ManeuverInfo);  
  8. }catch(Exception e){  
  9. Log.e(TAG, ”“,e);  
  10. }  
  11. return null;  
  12. }  
@Override
public JSONObject GetManeuverInfo() {
try{
JSONObject test=new JSONObject();
test.put("maomao", "value");
return test;
//return new JSONObject(bean.ManeuverInfo);
}catch(Exception e){
Log.e(TAG, "",e);
}
return null;
}




t.html裏的代碼:

[javascript] view plain copy
print?
  1. function testAPI(el){  
  2.     console.log(”———testAPI———”);  
  3.     eval(”var obj = ”+Navigation.GetManeuverInfo());   
  4.       
  5.     alert(’typeof:’+typeof(obj));  
  6.     alert(’maomao:’+obj.maomao);  
  7.     alert(’obj:’+obj);  
  8.   }  
        function testAPI(el){
            console.log("---------testAPI---------");
            eval("var obj = "+Navigation.GetManeuverInfo()); 

            alert('typeof:'+typeof(obj));
            alert('maomao:'+obj.maomao);
            alert('obj:'+obj);
          }

如果直接寫成  Navigation.GetManeuverInfo.maomao是會提示undefined,因爲js那邊只得到了一個string對象而已,它不知道maomao是個key。

通過eval將其轉化成表達式就可以調用obj.maomao得到value。


在此ps一下iOS,貌似人家支持webview很好,js可以直接獲取到json對象.



默認t.html加載會自動執行testAPI函數,結果如下:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章