我有一个方法应该将一些数据发布到 PHP 文件中:
-(void)submitForm {
NSLog(@"name=%@", formName.text); // returns correct value
NSString *post = [NSString stringWithFormat:@"name=%@&", formName.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://path/to/file"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@",responseString);
}
注意:我实际上并没有使用@"http://path/to/file"
. 出于隐私考虑,我省略了 URL。
我相信它正确连接到 PHP 脚本,因为我收到了我期望的响应。问题是,如果我echo
out $name
,我会得到一个空字符串。这是脚本:
<?php
include("config.php"); // Handles DB connection
$name = mysql_escape_string($_POST["name"]);
mysql_query("insert into objects(name) values('$name')") or die(mysql_error());
echo $name; // returns empty string
我所期望的只是 Obj-C 代码中的某种语法/逻辑错误,但我无法发现它。