问题描述
我有一个简单的JavaScript函数需要两个变量。我需要将我已经在Objective-C(iOS)应用程序中使用的两个变量传递给此javascript函数。我的代码运行的JavaScript是:
[webView stringByEvaluatingJavaScriptFromString:@onScan()];
javascript函数将这两个变量应用于HTML表单并提交。因为变量缺失,我当然会在表单中得到未定义的值。 8-)我一直无法找到关于这个的很多文档,但也许我在错误的地方看?
FWIW,我的Objective-C变量是字符串。我的JavaScript函数是 onscan(a,b)
更新:
我可以通过在每个传递给javascript函数的变量周围放置单引号来得到这个工作。更新的代码是:
[webView stringByEvaluatingJavaScriptFromString:@onScan('%@','%@'),a ,b]上;
stringByEvaluatingJavaScriptFromString:
需要一个 NSString
,所以你只需要使用 stringWithFormat:
和<$ c
$ b
NSString * stringOne = @first_parameter; $ c>%@
对象格式化程序如下所示:
NSString * stringTwo = @second_parameter;
NSString * javascriptString = [NSString stringWithFormat:@onScan('%@','%@'),stringOne,stringTwo];
[webView stringByEvaluatingJavaScriptFromString:javascriptString];
查看Apple的文档 NSString
,它是一个非常有用的对象!
I have a simple javascript function that takes two variables. I need to pass two variables that I already have in my Objective-C (iOS) application to this javascript function. My line of code to run the javascript is:
[webView stringByEvaluatingJavaScriptFromString:@"onScan()"];
The javascript function just applies the two variables to a HTML form and submits it. I'm of course getting undefined in my form since the variables are missing. 8-) I've been unable to find much documentation on this, but maybe I'm looking in the wrong places?
FWIW, my Objective-C variables are strings. My javascript function is onscan(a,b)
UPDATE:
I was able to get this working by placing single quotes around each of the variables being passed to the javascript function. The updated code is:
[webView stringByEvaluatingJavaScriptFromString:@"onScan('%@','%@')",a,b];
stringByEvaluatingJavaScriptFromString:
takes an NSString
so all you have to do is combine strings using stringWithFormat:
and the %@
object formatter like below:
NSString *stringOne = @"first_parameter";
NSString *stringTwo = @"second_parameter";
NSString *javascriptString = [NSString stringWithFormat:@"onScan('%@','%@')", stringOne, stringTwo];
[webView stringByEvaluatingJavaScriptFromString:javascriptString];
Check out Apple's documentation for NSString
, it's an insanely useful object!
这篇关于将Objective-C的变量传递给javascript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!