4

我有一个要求,其中objective C code should消耗WebService和收到的响应JSON format必须作为参数传递给javascript方法以进行进一步处理。我正在使用UIWebView它将在处理后显示适当的结果JSON response. 当我尝试将 JSON 字符串传递给Javascriptmethod.Javascript 方法不简单地接受输入。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSString *responseString = [[NSString alloc] initWithBytes:[resultData bytes] length:[resultData length] encoding:NSUTF8StringEncoding];
    NSLog(@"%@",responseString);
    [self returnResponseToJavaScriptMethods:responseString];
}


-(void)returnResponseToJavaScriptMethods:(NSString*)theResponse{
    [viewMainWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"retrieveServerResponse('%@')",theResponse]];
}

有什么我错过的吗?使用相同的方法可以正确传递简单的字符串。

更新responseData:对to进行编码就可以UTF8StringEncoding了。

[theResponse stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
4

2 回答 2

3

您可能需要在将 JSON 字符串发布到 javascript 之前对其进行 URL 转义。

尝试改变:

-(void)returnResponseToJavaScriptMethods:(NSString*)theResponse{
  [viewMainWebView stringByEvaluatingJavaScriptFromString:
  [NSString stringWithFormat:@"retrieveServerResponse('%@')",theResponse]];
}

-(void)returnResponseToJavaScriptMethods:(NSString*)theResponse{
  [viewMainWebView stringByEvaluatingJavaScriptFromString:
  [NSString stringWithFormat:@"retrieveServerResponse('%@')",
 [theResponse stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
} 

看看这是否对你有帮助。但是请注意,有更好(或更可靠)的方法来转义字符串,例如在此答案中给出的方法:How do I URL encode a string

于 2013-01-07T15:05:00.730 回答
0

javascript中不需要a retrieveServerResponse(),只需unescape(percentEscapedStringFromiOS)在iOS中对字符串进行百分比转义后使用

NSString *encodedString = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// CAVEAT: unescape(\"%@\") is important since "'" (single quote) isn't excaped by the above function!
NSString *jsString = [NSString stringWithFormat:@"myJSstring = unescape(\"%@\")", encodedString]];

NSString *jsResult = [self.webView stringByEvaluatingJavaScriptFromString:jsString];
于 2015-04-22T15:28:29.507 回答