通过iOS7中的JavaScriptCore进行HTTP请求

我正在尝试使用iOS7新功能之一 JavaScriptCore Framework.我可以从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 Framework中没有提供HTTP请求功能吗?如果是,我可以通过使用UIWebView的-stringByEvaluatingJavaScriptFromString来克服这个问题吗?如果我编译并在我的项目中包含另一个Javascript引擎(例如V8)怎么办?

解决方法

我的猜测是HTTP请求不是JavaScript Core的一部分,因为它实际上是浏览器的一部分,而不是JavaScript语言.
我认为JavaScript核心只包含ECMAScript定义中的内容.

如果你想要AJAX,那么WebView就是你的选择.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...