php,mysql,ios之間的json解析

php動態生成json

<?php

$page=$_GET["page"]; //獲取page
$page=($page-1)*10;
$conn=mysql_connect("127.0.0.1","root",""); //連接本機
mysql_select_db("xutianyu"); //本機數據庫
$sql="select * from news order by nid desc limit ".$page.",10";//從news表中查詢數據並倒敘顯示10個
$result=mysql_query($sql);
echo "{\"news\":[";
$hehe=1;
while($row=mysql_fetch_assoc($result)){ //數組接收返回
$arr=$row;
echo json_encode($arr);//編碼
if($hehe<10){
echo",";
}
$hehe++;
}
echo"]}";
mysql_close($conn);

?>


本文用得ios自帶的json解析

異步加載的兩個協議:

<NSURLConnectionDelegate,NSURLConnectionDataDelegate>

 NSString *weburl=[[[NSStringalloc]initWithFormat:@"http://10.2.145.162/testNews/jsonMessage.php?page=%d",page]autorelease];//建立到本機的連接

   NSURL *url=[NSURLURLWithString:weburl];//地址

    NSURLRequest *request= [NSURLRequestrequestWithURL:url];//請求對象

    NSURLConnection *conn=[NSURLConnectionconnectionWithRequest:requestdelegate:self];//開始發送請求連接

    [connstart];


實現協議裏面的方法

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

//    NSLog(@"得到響應");

     dic=[[NSMutableDictionaryalloc]init];//初始化字典

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data//接收數據

{

//    NSStringEncoding enc=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);

    dic=[NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableLeaveserror:nil];//解析接收到得數據並存放到字典中

}

然後就可以用啦
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章