我对 Xcode 和 Objective-C 真的很陌生......我收到一个 JSON 数组来显示我的 TableView 中的内容:
在我的-viewDidLoad
中:
[super viewDidLoad];
self.navigationItem.title = @"Kategorien";
NSURL *url = [NSURL URLWithString:@"http://www.visualstudio-teschl.at/apptest/kats.php"];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
if(jsonData != nil)
{
NSError *error = nil;
_kategorien = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
}
在我的cellForRowAtIndexPath:
方法中:
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *data = [self.kategorien objectAtIndex:indexPath.row];
cell.textLabel.text = [data objectForKey:@"KAT_NAME"];
return cell;
它工作得很好,并在我的表中显示了我的字符串(键 -> KAT_NAME)。
但是:我如何通过我的请求发送字符串?例如,我想通过我的请求发送“searchnumber = 2”,例如使用 javascript/jquery 的 ajax 请求?
我进行了搜索,但只能找到对于我的需求来说太困难(而且可能太大?)的示例...是否没有像我的请求和广告之类的简单方法,例如“sendWithData”,或者这种方法与我的完全不同简单的请求?
最佳答案
如果你想 POST 数据,你需要创建一个 NSMutableURLRequest 对象。无论如何,您都不应该使用 [NSData dataWithContentsOfURL:],因为这会创建同步请求并阻止 UI。尽管代码有点多,但这是正确的方法:
NSURL *url = [NSURL URLWithString:@"http://www.visualstudio-teschl.at/apptest/kats.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"searchnumber=2" dataUsingEncoding: NSASCIIStringEncoding];
[NSURLConnection sendAsynchronousRequest: request
queue: [NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *r, NSData *data, NSError *error) {
// do something with data
}];
关于objective-c - 又是: Easy way to request JSON with posting data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15987052/