Ios用javascript在webview中填充来自objective c的值
ios filling in webview with values from objective c using javascript
我需要填充一个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
相关文章:
- 如何使用jquery在填充自动完成的值后使文本框只读
- 如何使用jQuery选择下拉列表的值
- 如何在angularJS中编辑时,如果DB中的值为true,则设置复选框,如果值为false,则取消选中复选框
- 如何在php文件中获取$.post-ajax传递的值
- Javascript计数器变量未显示正确的值
- 从Rally获取一个特定的标记,以便计算另一个字段中的值
- 接受不在列表中的值-引导组合框
- 提交后保留下拉选择的值
- JavaScript 检查隐藏字段中的值并将其设置为隐藏字段值
- Meteor方法在客户端返回null,在客户端运行的相同方法返回正确的值
- 使用元素的值与innerHTML
- 获取HTML属性中CSS声明的值
- 如何在 Javascript 中将变量的值从字符串转换为整数
- Lodash 从值数组中查找数组中的值
- 从键值结构中获取数据,并将其与AngularJS中ng重复的值进行比较
- 将数组中的值插入到表中
- 使用Javascript使用数组检查文本框中的值
- 无法使用PHP动态设置下拉列表中的值
- Ios用javascript在webview中填充来自objective c的值
- 如何在Objective-C中获取HTML表的值