0

我想NSString从objective-c 向javascript 发送一些值。这是代码:

Javascript.html

<!DOCTYPE html>
<html>
    <head>
        <title>Sample Page that Writes Out an HTML Addition Table</title>
        <script src=“doc.js”&gt;</script>
    </head>
    <body>
    </body>
</html>

文档.js

function call(str){
    document.write('<table border="1" cellspacing="1" cellpadding="5">')
    for(i = 0; i < 4; i++){
        document.write('<tr>')
        for (j = 0; j < 3; j++){
            document.write('<td>'+str+'<img src= '+str+'> </img></td>')
        }
        document.write('</tr>')
    }
    document.write('</table>')
}

.m 文件

-(IBAction) show:(id) sender{

    NSString *htmlpath = [[NSBundle mainBundle] pathForResource:@"Javascript" ofType:@"html"];
    NSString *html =[NSString stringWithContentsOfFile:htmlpath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@",[[NSBundle mainBundle] bundlePath]] ];
    [[webView mainFrame] loadHTMLString:html baseURL:baseURl];

    NSString *jsTable=[NSString stringWithFormat:@"call('file:///Users/developer/Library/Billing/Barcodes/CO_BAT01_14.png')"];
    NSLog(@"jsTable = %@",jsTable);
    [webView stringByEvaluatingJavaScriptFromString:jsTable];
    [jsTable release];
}

我想从我的应用程序中将图像路径发送到 .js 文件。谁能帮我解决我的问题!!!提前致谢。

4

1 回答 1

1

在执行 javascript 之前,您应该等待 HTML 加载。为您的 WebView设置frameLoadDelegate并实现此方法:

- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
    NSString *jsTable=[NSString stringWithFormat:@"call('file:///Users/developer/Library/Billing/Barcodes/CO_BAT01_14.png')"];
    NSLog(@"jsTable = %@",jsTable);
    [sender stringByEvaluatingJavaScriptFromString:jsTable];
    [jsTable release];
}
于 2013-06-11T09:52:26.227 回答