繁体   English   中英

我想将JSON数据传递给与Web视图相关的javascript函数。 但是我无法从Javascript函数中获取响应数据

[英]I want to pass JSON data to javascript function related to web view. But I am unable to get the response data from the Javascript function

打印'b'值时,我变空了。 意味着我发送的数据是错误的。

我做错了吗?

这是我的代码

Swift 4.0

let inputPayload: Dictionary = ["wellname": ["answer": "firstName"]]

if JSONSerialization.isValidJSONObject(inputPayload) {
  do {
    let rawData =
      try JSONSerialization.data(withJSONObject: inputPayload, options: [])

    let b = webView.stringByEvaluatingJavaScript(from: "downloadComplete(\(rawData))") !
      print(b)
  } catch {

  }
}

这是我的Javascript函数

function downloadComplete(a) {
  return a.wellname.answer
}

Objective-C的

- (void)runJavaScriptCallback:(NSString *) jsonString {
    NSString *exec_template = @"downloadComplete(\'%@\');";
    NSString *exec = [NSString stringWithFormat:exec_template, jsonString];

    [webView evaluateJavaScript:exec completionHandler:nil];
}

斯威夫特4

func runJavaScriptCallback(jsonString: String) {
    webView.evaluateJavaScript("downloadComplete(\(jsonString))") { result, error in
        guard error == nil else {
            print(error)
            return
        }
    }
}

使用Javascript

var downloadComplete = (bridgeMsg) => {
  // escape newline character from iOS sdp
  bridgeMsg = bridgeMsg.replace(/\r?\n|\r/g, '\\r\\n');

  const msg = JSON.parse(bridgeMsg);
  // do whatever you want with the parsed json object
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM