简体   繁体   English

iOS Swift:当我将数组或字典之类的数据传递给Javascript时,它返回未定义的值吗?

[英]iOS Swift: When I pass data like array or dictionary to Javascript means it returns Undefined value?

In my project I have pass String from swift to JavaScript and displaying in alert it works perfectly. 在我的项目中,我已将String从swift传递到JavaScript,并在警报中显示它运行完美。 But if I have pass array or dictionary means returns undefined values like 但是如果我通过数组或字典意味着返回未定义的值,例如

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object] [对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象]

but I don't know how to fix the issue. 但我不知道如何解决该问题。

Here I have attached the screen shot for webview response. 在这里,我附上了Webview响应的屏幕截图。

我在警报中显示了返回的值

Here I have share my code what I am tried, 在这里,我分享了我尝试的代码,

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()
}

Here I share the Array Values, 在这里,我分享数组值,

[
  {
    "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"
  }
]

Here I have share my HTML code what I am tried, 在这里,我分享了我尝试过的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>

When Display unparsed Json means alert shows empty, Here I have attached the screenshot. 当“显示未解析的Json”表示警报显示为空时,在此附上了屏幕截图。

在此处输入图片说明

@user28434 is quite right. @ user28434是非常正确的。 just unparse it. 只是解析。 use var arrayData = param; 使用var arrayData = param;

Why not use WKWebView, 为什么不使用WKWebView,

'UIWebView' was deprecated in iOS 12.0: No longer supported; iOS 12.0中已弃用“ UIWebView”:不再受支持; please adopt WKWebView. 请采用WKWebView。

here is what I got: 这是我得到的:

图片

html code: 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>

native code 本机代码

 @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)
        }
    }

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

相关问题 iOS Swift 如何从 UIWebView 将 JSON 字符串和数组或字典传递给 Javascript? - iOS Swift How to pass JSON String and Array or Dictionary to Javascript from UIWebView? Javascript:当值未定义时,方法返回未定义 - Javascript: method returns undefined when value is not undefined 从Javascript数组读取数据将返回“未定义” - Reading Data from a Javascript Array returns 'undefined' JavaScript-获取数据属性值返回未定义 - JavaScript - Getting value of data attribute returns undefined Fetch 返回一个类型为 undefined 的类数组。 我如何获取其中的数据? - Fetch returns an array-like with type undefined. How do I get the data inside it? 当我尝试访问javascript数组时,正在填充未定义的值 - Undefined value is being populated when i try to access javascript array 当我在JavaScript中返回true时,它将返回未定义状态 - When I return true in Javascript, it returns as undefined 无法访问 Javascript 构造对象数组的实际值 - 返回未定义 - Cannot access the actual value of a Javascript array of constructed objects - returns undefined Javascript数组。 将计算值推入数组将返回未定义 - Javascript Arrays. Pushing a calculated value to an array returns undefined 具有对象数组的Javascript; 对象中的属性具有值,返回未定义 - Javascript with Array of Objects; Property in Object has Value, returns Undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM