我正在开发一个iPhone应用程序来显示来自php的数据。数据从Mysql数据库中获取,然后在php文件中编码为JSON格式:
include_once 'connectionIncl.php';
if(function_exists($_GET['method'])){
$_GET['method']();
}
function getSQLIntoJSONFormat()
{
$arr;
$sql = mysql_query("SELECT * FROM pecivo");
while($pecivo = mysql_fetch_assoc($sql)){
$arr[] = $pecivo['typ'];
}
$arr= json_encode($arr);
echo $_GET['jsoncallback'].'('.$arr.')';
}
// --- http://127.0.0.1:8887/TeplyRohlik/pecivo.php?method=getSQLIntoJSONFormat&jsoncallback=?当我从浏览器运行此命令时,它返回正确的数据:
(["sejra","knir","baba","vousy","sporitelna25"])另外,在iOS上有这样的代码:
NSString * urlString = [NSString stringWithFormat:@"http://192.168.0.10:8887/TeplyRohlik/pecivo.php?method=getSQLIntoJSONFormat&jsoncallback=?"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"%@",json);结果是……(null)。我不知道怎么才能让它工作...
发布于 2012-07-22 01:20:12
看起来你的PHP方法输出了JSONP。您可能要做的是将其更改为:
function getSQLIntoJSONFormat()
{
$arr;
$sql = mysql_query("SELECT * FROM pecivo");
while($pecivo = mysql_fetch_assoc($sql)){
$arr[] = $pecivo['typ'];
}
$arr= json_encode($arr);
echo $arr;
}您可以看到输出被包装在圆括号中,因为它期望在名为jsoncallback的请求中有一个GET参数,这将使输出看起来如下所示:
javascriptFunction(["a","b","b"])这不是你想在你的iOS设备上看到的。您只需要数组的原始JSON字符串,没有包装在回调函数调用中。
https://stackoverflow.com/questions/11594158
复制相似问题