以下是一份工作样本。
function process(json) { // Do whatever you want with the json object // Example console.log(json[0].name); }
<!DOCTYPE html> <html> <head> <meta charset='UTF-8' />" <meta name='viewport' content='width=device-width, initial-scale=1'> <link rel=\"stylesheet\" href=\"roboto.css\"> <link rel=\"stylesheet\" href=\"webViewLightTheme.css\"> </head> <body> <img src="http://x.y.z/wp-content/uploads/2017/12/android-smart-text-selection-350x175.jpg" onClick="process([{'name':'John', 'age': '30', 'city':'New York'}]);" />" </body> </html>
非推荐:
console.log('onclick= '+document.images[0].getAttribute('onclick')); window.JavaScriptInterface={} window.JavaScriptInterface.showImages=function(x){console.log(x)} document.images[0].click()
<img src="http://x.y.z/wp-content/uploads/2017/12/android-smart-text-selection-350x175.jpg\" onclick='window.JavaScriptInterface.showImages("[{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}]")'>
更好用 addEventListener 像@Reijo那样,
addEventListener
试试吧 JSON库
const img = document.getElementById('img'); img.addEventListener('click', function() { let jsonString = '"[{"name":"John","age":30,"city":"New York"}]'; window.JavaScriptInterface.showImages(JSON.parse(jsonString)); });
JSON数据中的双引号会干扰属性的引号。您需要再次转义JSON数据中的除法引号(添加一个 \ 因此,我们没有看到封闭的内容,并且HTML解析器知道JSON数据中的双引号是您传入的数据的一部分,并不意味着结束引用。
\
编辑:或者您可以使用单引号,就像在视口标记中那样,因为HTML和Javascript都不区分单引号和双引号。这可能会使整个事情变得更容易混淆和更容易阅读。