2015-06-16 85 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