2015-06-16 86 views
0

有什麼辦法可以將JSONObject從android傳遞給javascript。我們正在使用WebView.evaluateJavascript mehtod,並且只能發送String類型的對象。在JS中,如果我們檢查方法參數; typeof(數據),那麼它顯示爲字符串,但在iOS中它將typeof(data)顯示爲OBJECT。從Android/iOS本地傳遞json對象到javascript

在android和iOS中,我們都傳遞String和NSString。

JS方法是:

response: function(id, err, data) { 
     var dataObj; 
     if(typeof(data) == 'string'){ 
      dataObj = JSON.parse(data || '{}'); 
     } 
    } 

的Android電話:

String responseStr = "{\"ok\":\"ok\"}"; 
String nativeToWebMethod = "javascript:window.nativeService.response("1",'','"+responseStr+"')"; 
webView.evaluateJavascript(nativeToWebMethod, null); 

回答

0

我找出來的問題進行最後的代碼,它是在我發送數據的方式:

String nativeToWebMethod = "javascript:window.nativeService.response("1",'','"+responseStr+"')"; 

String nativeToWebMethod = "javascript:window.nativeService.response("1",'',"+responseStr+")"; 
被替換

刪除了responseStr的單引號。

1

只需把它就像你加載網址:

private void loadJS(String jsonResponse){ 

    mWebView.loadUrl("javascript:" + "(function(){" + "yourJsMethodName" + "(" +jsonResponse + ");" + "})()"); 

} 

這將執行一個JS代碼,將調用一個名爲yourJsMethodName的函數,並將傳遞JSON作爲參數。

考慮在主線程

+0

我的代碼已經可以調用js方法,並且可以向它發送字符串參數。問題在於將json作爲JSONObject發送。 – Manish

+0

我沒有看到你的觀點。可以說你把這個傳遞給你的webview - > theFunction({「ok」:「ok」}),這裏你傳遞一個JSON對象,它不同於 - > theFunction(「{\」ok \「:\」好\」}」);在這裏你傳遞一個字符串。東西在於你如何構建你的responseStr。正如你所看到的,你將它作爲'responseStr'傳遞,只需簡單的昏迷。 JS會將其解釋爲String。但是IOS有時候很特別。 IOS可能直接將字符串解釋爲JSON – jDur