坚持为什么我的 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();
?>