javascript - iOS swift : When I pass data like array or dictionary to Javascript means it returns Undefined value?

标签 javascript ios swift stringbyevaluatingjavascr

在我的项目中,我将 String 从 swift 传递到 JavaScript 并在警报中显示它完美地工作。但是,如果我传递数组或字典意味着返回未定义的值,如

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

但我不知道如何解决这个问题。

这里我附上了 webview 响应的屏幕截图。

I displayed the returned value in alert

在这里我分享了我的代码,我尝试过,

override func viewDidLoad() {
    super.viewDidLoad()
    webView.delegate = self
    loadHTMLFromBundle()
}
func loadHTMLFromBundle(){
    let url = Bundle.main.url(forResource: "index", withExtension: "html")
    let urlRequest:URLRequest = URLRequest(url:url!)
    self.webView.loadRequest(urlRequest)
}

func getComponents() {
    guard let path = Bundle.main.path(forResource: "components", ofType: "txt") else { return }
    let url = URL(fileURLWithPath: path)

    let jsonData = try! Data(contentsOf: url)
    tempComponentArray = try! JSONSerialization.jsonObject(with: jsonData, options: []) as! NSArray
    print("jsonDict:\n \(tempComponentArray)")

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: tempComponentArray, options: [])

        //Convert back to string. Usually only do this for debugging
        if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
            print(JSONString)
            let urlString:NSString = NSString(format: "myNewFunction(%@)", JSONString)
            print("urlString: ",urlString)
            self.templateFormStr = JSONString
            print(self.templateFormStr)
            let encodedStr = self.webView.stringByEvaluatingJavaScript(from: "myNewFunction('\(self.templateFormStr)')")   **-----------> Here I passed or evaluate the data to javascript**
            print("encodedStr: ",encodedStr!)
        }

    } catch {
        print(error.localizedDescription)
    }
}

@IBAction func loadJSBtnTapped(_ sender: Any) {
    getComponents()
}

这里我分享数组值,

[
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "North",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "textField"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "South",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "south"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "East",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "east"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "West",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "west"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "Easements / Encroachments",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "easementsEncroachments"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "Soil ans Sub-Soil Conditions",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "soilAnsSubSoilConditions"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "Environmental Conditions",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "environmentalConditions"
  }
]

这里分享一下我尝试过的HTML代码,

<!DOCTYPE html>
<html>
    <p>Click the button to display an alert box.</p>
    <script>
    function myNewFunction(param) {
        var arrayData = JSON.parse(param);
        alert(arrayData)
    }
    </script>
<body>
    <button onclick="myFunction()">Try it</button>
</body>
</html>

当Display unparsed Json表示alert显示为空时,我附上截图。

enter image description here

最佳答案

@user28434 说得很对。只是解析它。使用 var arrayData = param;

为什么不用WKWebView,

'UIWebView' was deprecated in iOS 12.0: No longer supported; please adopt WKWebView.

这是我得到的:

image

html代码:

<!DOCTYPE html>
<html>
    <p>Click the button to display an alert box.</p>
    <script>
    function myNewFunction(param) {
        var arrayData = param;
        alert(arrayData)
    }
    </script>
<body>
    <button onclick="myFunction()">Try it</button>
</body>

本地代码

 @IBOutlet weak var webView: UIWebView!


override func viewDidLoad() {
    super.viewDidLoad()
    webView.delegate = self
    loadHTMLFromBundle()
    }
    func loadHTMLFromBundle(){
        let url = Bundle.main.url(forResource: "index", withExtension: "html")
        let urlRequest:URLRequest = URLRequest(url:url!)
        self.webView.loadRequest(urlRequest)
    }

    func getComponents() {
        guard let path = Bundle.main.path(forResource: "components", ofType: "txt")
            else {



                return }
        let url = URL(fileURLWithPath: path)

        let jsonData = try! Data(contentsOf: url)
        let tempComponentArray = try! JSONSerialization.jsonObject(with: jsonData, options: []) as! NSArray
        print("jsonDict:\n \(tempComponentArray)")

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: tempComponentArray, options: [])

            //Convert back to string. Usually only do this for debugging
            if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
                print(JSONString)
                let urlString:NSString = NSString(format: "myNewFunction(%@)", JSONString)
                print("urlString: ",urlString)
                let templateFormStr = JSONString
                print(templateFormStr)
                let encodedStr = self.webView.stringByEvaluatingJavaScript(from: "myNewFunction('\(templateFormStr)')")


                print("encodedStr: ",encodedStr!)
            }

        } catch {
            print(error.localizedDescription)
        }
    }

关于javascript - iOS swift : When I pass data like array or dictionary to Javascript means it returns Undefined value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53281582/

相关文章:

swift - 使用 Xcode 在 MacOS 上进行服务器端 Swift 开发,在 Docker Ubuntu 上进行测试 : How do I not clean/recreate each time?

ios - 尝试使用协议(protocol)使 View 可拖动时应用程序崩溃

javascript - 从同一个文件和不同文件调用nodejs函数

javascript - 根据服务器的响应在 Angular 中创建动态表单

ios - 如何使用 ALAssetsLibrary 在 iOS 8 上枚举所有照片

java - "users"的 Realm IO应用

ios - 设置 UIImageView 图片影响布局约束

javascript - 如何禁用 dijit.form.Select 中的单个选项?

javascript - jQuery slider 最小范围

ios - 尝试在 Swift 中使用 AutoLayout curl / curl 两个 View