【发布时间】:2013-06-04 05:44:06
【问题描述】:
过去几天我一直在为此苦苦挣扎;我正在尝试将数组发布到 PHP。我可以成功发送它,但它没有使用后变量(我正在尝试使用变量键“json”...使用此代码,我在 php 中收到数组:
目标-C
NSError *error;
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects: @"one", @"two", @"three", nil] forKeys: [NSArray arrayWithObjects: @"a", @"b", @"c", nil]];
NSArray *jsonArray = [NSArray arrayWithObject:jsonDictionary];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonArray options:NSUTF8StringEncoding error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"somewebservicelocation/arrayTest.php?json="]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *response = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"response: %@",response);
PHP
$handle = fopen('php://input','r');
$array = fgets($handle);
echo $array;
if(isset($array))
{
echo "success";
}
else
{
echo "failure";
}
如果我使用这个 PHP,使用 _POST,我不会得到爱:
$rawJsonData = $_POST['json'];
$array = json_decode(stripslashes($rawJsonData),true);
echo $array;
if(isset($array))
{
echo "success";
}
else
{
echo "failure";
}
...我已经用了好几天了——在 Stack Overflow 上,我知道我需要在请求的正文中包含变量和数据,但我就是无法让它工作。我究竟做错了什么?你如何以不同的方式解决这个问题?让我免于这种头痛......
【问题讨论】:
-
我不确定您为什么需要
_POST演绎版,但我在答案的后半部分提供了一个示例。 -
a) 有时我会将其他变量与数组一起发送(是的,我知道我可以将数组操作得更大,但我认为这不是最佳做法)。 b)因为我确信这是可能的......
-
正如我在下面所说的,我绝对更喜欢构建我 json 编码的
NSDictionary来捕获我想要传递的所有这些项目。_POST结构感觉就像是一种网络浏览器表单技术,它不适合 JSON 擅长的这种计算机到计算机的通信(尽管这样做可能会被扭曲)。这两种技术都有效,但我倾向于整合 JSON 方法,而不是 _POST 和 JSON 方法的混合。但使用适合您的。
标签: php objective-c arrays http-post