2

坚持为什么我的 json 响应在某些情况下重复两次(无法隔离),从而导致我的 jsonData 为(null)。我对 Android 使用相同的 php,但只有我的 iOS 看到了这个问题。这是我的 Objective-C 代码,它会产生两次响应——有时:

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];

        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSLog(@"Response code: %d", [response statusCode]);
        if ([response statusCode] >=200 && [response statusCode] <300)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);

            SBJsonParser *jsonParser = [SBJsonParser new];
            NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
            NSLog(@"jsonData: %@",jsonData);

这是php:

//retrieve the login details via POST
$username = $_POST ['username'];

$query = mysql_query ("SELECT * FROM inputs
WHERE user = '$username' AND ts = (SELECT MAX(`ts`)FROM inputs WHERE user =    '$username')");

//create a while loop that places the returned data into an array
while ($list = mysql_fetch_assoc($query)){

//store the returned data into a variable
$output = $list;

//encode the returned data in JSON format
echo json_encode($output);

}
//close connection
mysql_close();

?>
4

1 回答 1

0

构建输出数组,然后输出你的 json。可能发生的情况是您第一次发送有效的 json,然后当您继续 ech 时,它变得无效,因为您的字符串如下:

{test: 1}{hello: 2}

不是有效的 json。

$output = array();

//create a while loop that places the returned data into an array
while ($list = mysql_fetch_assoc($query)){

//store the returned data into a variable
$output[] = $list;
}

//encode the returned data in JSON format
echo json_encode($output);
于 2013-08-11T00:56:04.917 回答