【问题标题】:ios filling in webview with values from objective c using javascriptios使用javascript使用来自目标c的值填充webview
【发布时间】:2013-05-24 16:05:45
【问题描述】:

我需要用存储在目标 C 中的变量填充 html webview。

我相信我需要使用:

[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>

【问题讨论】:

    标签: javascript iphone ios


    【解决方案1】:

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

    对象 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>
    

    【讨论】:

      【解决方案2】:

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

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

      编写 Javascript 以将数据放入 HTML 字符串是 easy

      【讨论】:

      • methodName是javascript函数名吗?
      • 我的 html 输出为空白。你能看看我更新的代码,看看我哪里出错了吗?
      • 对不起,你还没有写方法。看看这个(stackoverflow.com/questions/5400230/… 使用 JQuery 不过它应该给你一个想法。
      • 我再次更新了我的 javascript,现在当视图确实出现时,html 消失了,我留下了一个空白屏幕,只有我传递的变量名。 (在这种情况下,“John”)还将 methodName([%@]) 更改为 ('%@) 不确定这是否会影响任何事情
      【解决方案3】:

      您可以访问代码中的原始 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,这里有一个例子: How to control UIWebView's javascript

      【讨论】:

      • 虽然这会并且确实有效,但添加所有适当的引号以及以正确的格式获取它会非常耗时。
      猜你喜欢
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      相关资源
      最近更新 更多