簡體   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