Ios用javascript在webview中填充来自objective c的值

ios filling in webview with values from objective c using javascript

本文关键字:objective 的值 填充 javascript webview Ios      更新时间:2023-09-26

我需要填充一个html webview与变量,我已经存储在objective c。

我认为我需要使用:

[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"John", firstName];

但不确定在那里放什么,我的javascript需要什么来实现传递的变量。

这里是我的一些HTML来帮助你理解:

<ul><li><span>First Name:</span> first name needs to go here</li>
  <li><span>Last Name:</span> last name needs to go here</li>

更新代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"idcard" ofType:@"html"]isDirectory:NO]]];
}
-(void)viewDidAppear:(BOOL)animated
{
    NSString *str  = @"John";
    NSString *script = [NSString stringWithFormat:@"myFunc('%@')", str];
    [self.webView stringByEvaluatingJavaScriptFromString:script];

}
更新2:

javascript/html:

<ul><li><span>Policy Number:</span>        
<script> function myFunc(str)
        {
            document.write(str)  }
        </script>

我最终使用了不同的js方法并使用了,希望这对某人有帮助。

obj c:

NSString *str  = @"John";
NSString *script = [NSString stringWithFormat:@"document.getElementById('name').innerHTML = '%@';", str];
[self.webView stringByEvaluatingJavaScriptFromString:script];

js:

<li><span>Name:</span>   <span id = 'name'>name goes here</span>
      </li>

基本上需要一个javascript方法来将数据添加到HTML字符串中。有了函数之后,将数据传递给它就相当简单了,

NSString *script = [NSString stringWithFormat:@"methodName([%@])", data]
[self.webView stringByEvaluatingJavaScriptFromString:script];

编写Javascript将数据放在HTML字符串中是很容易的。

您可以访问代码中的原始HTML字符串吗?如果有,你能做到吗?

UIWebView *webview = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webview];
NSString *htmlString = [NSString stringWithFormat:@"<html>'
<ul><li><span>First Name:</span> %@</li>'
<li><span>Last Name:</span> %@</li>'
</html>", @"John", @"Smith"];
[webview loadHTMLString:htmlString baseURL:nil];

如果你想使用JavaScript,这里有一个例子:如何控制UIWebView's javascript