iOS UIWebView Javascript-插入数据-接收回调?
我有一个网页。我有一个javascript文件,可以做很多事情。在应用程序中,我有一个NSString,其中包含一些需要在javascript文件中处理的关键数据。如何将字符串值放入html中的某个位置,以便javascript能够读取它 此外,javascript在执行操作(如按下按钮)时会生成某些数据,如何从webview/javascript检索数据,以便将其存储在应用程序中iOS UIWebView Javascript-插入数据-接收回调?,javascript,iphone,ios,Javascript,Iphone,Ios,我有一个网页。我有一个javascript文件,可以做很多事情。在应用程序中,我有一个NSString,其中包含一些需要在javascript文件中处理的关键数据。如何将字符串值放入html中的某个位置,以便javascript能够读取它 此外,javascript在执行操作(如按下按钮)时会生成某些数据,如何从webview/javascript检索数据,以便将其存储在应用程序中 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSS
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
听起来正是你需要的方法。例如,如果需要与JavaScript交互的输入和输出可以通过一个方法完成,则可以将一个值传递到JavaScript中,并使用以下代码获得结果:
NSString* jsCode = [NSString stringWithFormat:@"doSomething('%@')", dataToPass];
NSString* resultFromJavaScript = [webView stringByEvaluatingJavaScriptFromString:jsCode];
您可以调用javascript方法并通过使用
NSString *selectedValue = [webViewInstance stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getAndReturnRadioValue(%d)", questionCounterIntValue]];
但要从javascript中触发,需要使用一种变通方法
实现以下webViewDelegate方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSLog(@"passed data from web view : %@",[[request URL] query]);
if([[[request URL] query] isEqualToString:@"clickedOnLineNo"])
{
//Do your action here
}
}
您必须从javascript方法导航到假URL,如
window.location = "someLink://yourApp/form_Submitted:param1:param2:param3";
单击按钮或执行所需操作
你可以看看我对这个问题的回答
您好,我们可以将数据从objective c发送到javascript,并且可以轻松地从javascript回调 Objective-C-->javaScript 在Objective-C类中
NSData *locationCountData = [NSJSONSerialization dataWithJSONObject:locationCount options:NSJSONWritingPrettyPrinted error:nil];
NSString *locationCountString = [[NSString alloc] initWithData:locationCountData encoding:NSUTF8StringEncoding];
NSData *locationCountData = [NSJSONSerialization dataWithJSONObject:locationCount options:NSJSONWritingPrettyPrinted error:nil];
NSString *locationCountString = [[NSString alloc] initWithData:locationCountData encoding:NSUTF8StringEncoding];
NSString *str = [NSString stringWithFormat:@"testFunction(%@,%@)",locationCountString, locationsListString];
[self.myWebView stringByEvaluatingJavaScriptFromString: str];
在JavaScript文件中
<script type="text/javascript">
function testFunction(locationCount,locationList)
{
alert(locationCount + locationList);
}
</Script>
函数testFunction(locationCount、locationList)
{
警报(位置计数+位置列表);
}
您能否进一步阐述如何从javascript获取数据?例如,如果您单击html中的一个按钮,它将触发一个javascript函数。这个函数有一个我需要的返回值。如何获取该返回值?正如我在回答中提到的,从JS函数导航到URL-它将触发委托方法。我缺少“”周围的%@。。。Uff,1小时后!非常感谢。