我有發送請求到URL發佈了一個名爲變量的iPhone應用程序提交:PHP - > JSON - > iPhone
+(NSMutableArray*)getQuestions:(NSString*)section from: (NSString*) url{
NSMutableArray *questions = [[NSMutableArray alloc] init];
//connect to database given by url
//NSError *error = nil;
//NSURLResponse *response = nil;
NSMutableString* myRequestString = [[NSMutableString string]initWithFormat:@"section=%@", section];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: url]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPMethod: @"POST"];
//post section
[request setHTTPBody: myRequestData];
//store them in the array;
return [questions autorelease];
}
我的PHP文件:
<?php
//connect to database
function connect() {
$dbh = mysql_connect ("localhost", "abc1", "12345") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
//store posted data
if(isset($_POST['section'])){
$dbh = connect();
$section = $_POST['section'];
$query = mysql_query("SELECT * FROM QUESTIONS WHERE sectionId = $section;") or die("Error: " . mysql_error());;
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
echo '{"questions":'.json_encode($rows).'}';
mysql_close();
}
?>
我建立了一個模型類(Question)在目標c中具有每行元素在行關聯數組中具有的確切屬性。
我的問題是:
1)我如何可以讀取目標C中的回顯的JSON數組元素和它們的相對屬性?
2)如何創建一個Question對象數組並將其映射到rows數組中的元素?我需要在我的方法「+(NSMutableArray *)getQuestions:(NSString *)部分:(NSString *)url」中寫入以捕獲來自PHP(回聲)的回覆?
編輯:
這裏是PHP的輸出:
http://dev.speechlink.co.uk/David/get_questionstest.php
UPDATE
使用ASIHTTPRequest更改方法 - 不能deserialise JSON字符串:
//method to
+(NSDictionary*)getQuestions:(NSString*)sectionId from: (NSString*) url{
NSDictionary *questions;
NSURL *link = [NSURL URLWithString:url];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request setPostValue:sectionId forKey:@"section"];
NSError *error = [request error];
[request startAsynchronous];
if (!error) {
//NSString *response = [request responseString];
//store them in the dictionary
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
questions = [json objectFromJSONString];
NSLog(@"Data: %@", questions); //outputs Data: (null)
[json release];
[request release];
}else{
//UIAlertView to warn users there was an error
}
return questions;
}
嗨,感謝您的回覆。當我對NSLog做的問題得到null時,爲什麼會這樣呢? – user559142
然後你沒有正確地獲取你的數據。嘗試記錄'問題'(從這行創建:'NSDictionary * questions = [json objectFromJSONString];')。看看是否包含數據。 –
嗨,那也返回null。我不知道我在哪裏;錯誤地獲取數據。當在瀏覽器中查看鏈接到HTML(刪除發佈數據的所有集)時,JSON字符串會正確顯示。 – user559142