0

我是 iPhone 的新手,我正在尝试将 NSMutable 数组转换为 json 字符串,然后使用请求将此字符串发送到 php 文件,然后使用响应 NSLog 再次打印它以确保它已成功发送。所以我在viewDidLoad中写了如下代码

NSString *phpUrl = @"http://dt-works.com/eman/bookMarks.php";

NSMutableArray *arrayKey = [[NSMutableArray alloc] initWithObjects:@"one", @"two", @"three", nil];
NSMutableArray *arrayValue1 = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", nil]; 
NSMutableArray *arrayValue2 = [[NSMutableArray alloc] initWithObjects:@"11", @"22", @"33", nil]; 

NSDictionary *theReqDictionary1 = [NSDictionary dictionaryWithObjects:arrayValue1 forKeys:arrayKey];
NSDictionary *theReqDictionary2 = [NSDictionary dictionaryWithObjects:arrayValue2 forKeys:arrayKey];

NSMutableArray *myArray = [NSMutableArray arrayWithObjects:theReqDictionary1,theReqDictionary2, nil];

NSString *jsonString = [myArray JSONRepresentation];

NSLog(@"%@", jsonString);



 NSDictionary *questions = nil;
NSURL *link = [NSURL URLWithString:[phpUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request setPostValue:jsonString forKey:@"jsonString"];
[request setTimeOutSeconds:120];
[request setDelegate:self];
NSError *error = [request2 error];
[request2 startSynchronous];

if (!error) { 
    NSData *response = [request responseData];
    NSString *json = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    questions = [json objectFromJSONString];
    NSLog(@"Data: %@", questions);

} 

bookMarks.php 中的代码是:

$handle = fopen('php://input','r');
$jsonInput = $_POST['jsonString'];
print_r($jsonInput);

但它给了我:

[{"one":"1","two":"2","three":"3"},{"one":"11","two":"22","three":"33"}]
Data: (null)

我希望数据为: [{"one":"1","two":"2","three":"3"},{"one":"11","two":"22 ","three":"33"}] 怎么做??

4

1 回答 1

0

试试这个,而不是使用密钥发布 JSON 字符串,您需要将其作为数据发布到您的脚本中以供读取。目前在您的脚本中,您甚至没有使用 $handle 来做任何事情......

NSURL *link = [NSURL URLWithString:[phpUrl     stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request appendPostData:[jsonString  dataUsingEncoding:NSUTF8StringEncoding]]; 
[request setTimeOutSeconds:120];
[request setDelegate:self];

还有你的php代码..

$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$decoded = json_decode($jsonInput,true);
print_r($decoded);
于 2012-05-27T14:49:06.780 回答