从iOS传递字典数组到javascript函数

时间:2015-02-27 08:22:35

标签: javascript ios uiwebview

我的javascript函数需要这种类型的数组:

var data = [{
                                    "sale": "202",
                                    "year": "2000"
                                    }, {
                                    "sale": "215",
                                    "year": "2002"
                                    }, {
                                    "sale": "179",
                                    "year": "2004"
                                    }, {
                                    "sale": "199",
                                    "year": "2006"
                                    }, {
                                    "sale": "134",
                                    "year": "2008"
                                    }, {
                                    "sale": "176",
                                    "year": "2010"
                                    }];

我想将此数组作为[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"js_func(%@, %@)", y1Arr, y2Arr]];

中的参数传递

我正在以这种格式传递字典数组:

({
    x = "663.78";
    y1 = "-0.000";
},
{
    x = "663.88";
    y1 = "0.005";
},
{
    x = "663.98";
    y1 = "0.019";
},
{
    x = "664.08";
    y1 = "-0.001";
}
)

但它不起作用......

1 个答案:

答案 0 :(得分:1)

你不应该直接在stringWithFormat中传递你的数组,你应该首先将它们转换为json对象,然后将这些json对象(作为字符串表示)传递给stringWithFormat

NSData *data1 = [NSJSONSerialization dataWithJSONObject:y1Arr options:0 error:NULL];
NSString *y1ArrStr = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];

NSData *data2 = [NSJSONSerialization dataWithJSONObject:y2Arr options:0 error:NULL];
NSString *y2ArrStr = [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];

[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"js_func(%@, %@)", y1ArrStr, y2ArrStr]];