开发者

ASIHTTPRequest Multiple POST parameters

开发者 https://www.devze.com 2023-02-19 11:38 出处:网络
I\'m using ASIFormDataRequest to post data to a server, and I need to post an array of values (strings in the example below). I\'m using an enumerator to loop through each and add them to the request,

I'm using ASIFormDataRequest to post data to a server, and I need to post an array of values (strings in the example below). I'm using an enumerator to loop through each and add them to the request, bu开发者_开发技巧t only the last one comes through - the behaviour you'd expect for setPostValue, not addPostValue.

Any idea why only one value is coming through?

NSEnumerator *pupilEnumerator = [pupils objectEnumerator];
id pupil;
while ((pupil = [pupilEnumerator nextObject])) {
  [request addPostValue:pupil forKey:@"pupils"];
}

Note this also occurs for addFile and addPostData.

Cheers.


Your loop just keeps replacing the "pupils" value. Get rid of the loop and try [request addPostValue:pupils forKey:@"pupils"];


If I were you I'd bundle up your pupils object into a JSON string (I'd use JSON Framework, but there are other options), and put that in the post body.

Or, if you're posting to a PHP script, you CAN post multiple values straight into an array, by putting "[]" after the key name. So, still inside your loop, you could say [request addPostValue:pupil forKey:@"pupils[]"];, and then your posted-to script will have an array called $pupils that will contain all those values.


I faced a similar problem where I had multiple parameters and one of them (only one of the parameters) was supposed to be an array. The easier way I found was to add the values for that array to an NSMutableArray and then transfer those values to the parameter:

//Don't forget to set this array to retain its values in the property
self.arrSelected = [[NSMutableArray alloc]initWithArray:nil];

if(switch1.selected){
    [self.arrServicesSelected addObject:@"value1"];
}
if(switch2.selected){
    [self.arrServicesSelected addObject:@"value2"];
}
if(switch3.selected){
    [self.arrServicesSelected addObject:@"value3"];
}

Then you just need to go through the array and add the values to the POST parameter. Make sure you add them to different indices. I have seen some people adding to the [] without the index and that will not work as it will add only the last one. If you don't use the [] you will only add the first one.

for(int i=0; i< [self.arrSelected count];i++){
    [requestPOST setPostValue:[self.arrSelected objectAtIndex:i]  forKey:[NSString stringWithFormat:@"chk_parameter_serv[%i]", i]];
}

You can also use the forin syntax:

int i=0;
for(NSString *strValue in self.arrSelected)
    [requestPOST setPostValue:strValue  forKey:[NSString stringWithFormat:@"chk_parameter_serv[%i]", i++]];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号