就像标题说的那样。。
我的 NSDictionary initWithObjectsAndKeys for JSON,使用 POST 方法,通过 PHP 代码进行 MySQL 查询,通过使用 json_encoding 和 json_decoding 在我的 SQL 数据库中创建空数据,只是 ID int 每次我发布时都会自动增加!
我的 Xcode 代码:
-(IBAction)setJsonFromData:(id)sender
{
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys: @"Welcome", @"title", @"Hello", @"article", @"123456789", @"timestamp", nil];
if([NSJSONSerialization isValidJSONObject:jsonDict])
{
NSError *error = nil;
NSData *result = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
if (error == nil && result != nil) {
[self postJSONtoURL:result];
}
}
}
-(id)postJSONtoURL:(NSData *)requestJSONdata
{
NSURL *url = [NSURL URLWithString:@"http://test.com/json.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestJSONdata length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestJSONdata];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"RESULT: %@", requestJSONdata);
if (error == nil)
return result;
return nil;
}
我的PHP代码:
if (isset($_REQUEST))
{
$json = $_REQUEST;
$data = json_decode($json);
$title = $_REQUEST['title'];
$article = $_REQUEST['article'];
$timestamp = $_REQUEST['timestamp'];
mysql_query("INSERT INTO news (title, article, timestamp) VALUES ('$title->title','$article->article','$timestamp->timestamp')");
}
mysql_close();