通常,当我想使用javascript将HTML字符串加载到webview中时,我会使用类似的东西......
NSString *htmlString = @"HTML String";
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('elementid').innerHTML = \"%@\";", htmlString]];
虽然这似乎适用于小字符串,但当字符串相对较大时它没有效果。显然,有一个长度限制。
所以,我的问题是,如果有人知道如何在不重新加载webview的情况下将大字符串加载到UIWebView中?
更新:有点清楚,在我的情况下,webview已经加载,我只是想替换它的内容而不必重新加载它,主要是因为重新加载webview不够快我的使用。
答案 0 :(得分:5)
我能够通过stringByEvaluatingJavaScriptFromString
传递极长的字符串,所以我怀疑这是问题所在。 (注意我正在为osx编写,而不是可能有所作为的ios)
可能是你没有正确地转义html所以它被作为无效的javascript传递,这可能不会发生任何事情。在将字符串传递给javascript之前,我正在对字符串执行以下操作:
content = [content stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
content = [content stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
content = [content stringByReplacingOccurrencesOfString:@"\r" withString:@""];
NSString *js = [NSString stringWithFormat:@"set_content(\"%@\")", content];
[ web_view stringByEvaluatingJavaScriptFromString: js ];
我不知道是否所有这些都是必要的,或者它是否可以更简洁地写出来(我对目标c非常新),但它似乎对我来说很好。
答案 1 :(得分:1)
如果HTML在文件中,您可以这样做:
NSString *path = [[NSBundle mainBundle] pathForResource: @"MyHTML" ofType: @"html"];
NSData *fileData = [NSData dataWithContentsOfFile: path];
[webView loadData: fileData MIMEType: @"text/html" textEncodingName: @"UTF-8" baseURL: [NSURL fileURLWithPath: path]];
如果你真的想加载一个HTML字符串,试试这个:
NSString *embedHTML = @"<html><head></head><body><p>Hello World</p></body></html>";
[webView loadHTMLString: embedHTML baseURL: nil];