【发布时间】:2013-11-18 16:42:00
【问题描述】:
我正在尝试使用 iOS7 的一项新功能,即 JavaScriptCore 框架。我可以从 Javascript 成功输出 helloWorld 字符串,但我感兴趣的是在 Javascript 中执行 HTTP POST,然后将响应传递给 Objective-C。不幸的是,当我在 Javascript 中创建 XMLHttpRequest 对象时,我得到了 EXC_BAD_ACCESS (code=1, address=....)。
这里是 Javascript 代码 (hello.js):
var sendSamplePost = function () {
// when the following line is commented, everything works,
// if not, I get EXC_BAD_ACCESS (code=1, address=....)
var xmlHttp = new XMLHttpRequest();
};
var sayHello = function (name) {
return "Hello " + name + " from Javascript";
};
这是我 ViewController 中的 Objective-C 代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
JSContext *context = [[JSContext alloc] initWithVirtualMachine:[[JSVirtualMachine alloc] init]];
NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"hello" ofType:@"js"];
NSLog(@"scriptPath: %@", scriptPath);
NSString *script = [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"script: %@", script);
[context evaluateScript:script];
JSValue *sayHelloFunction = context[@"sayHello"];
JSValue *returnedValue = [sayHelloFunction callWithArguments:@[@"iOS"]];
// this works!
self.label.text = [returnedValue toString];
JSValue *sendSamplePostFunction = context[@"sendSamplePost"];
// this doesn't work :(
[sendSamplePostFunction callWithArguments:@[]];
}
会不会是 JavaScriptCore 框架中没有提供 HTTP 请求功能?如果是,我可以通过使用UIWebView 的-stringByEvaluatingJavaScriptFromString: 来克服这个问题吗?如果我在我的项目中编译并包含另一个 Javascript 引擎(例如 V8)怎么办?
【问题讨论】:
标签: ios objective-c httprequest javascriptcore