2010-09-07 281 views
0

我正在開發一個使用JSON框架的iPhone應用程序,我正在調用一個PHP腳本來更新本地服務器上的MySQL數據庫。使用這些代碼:如何從iPhone發佈請求獲取json數據

NSString *jsonString = [sendData JSONRepresentation]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
NSString*post = [NSString stringWithFormat:@"&json=%@", jsonString]; 
NSData*postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO]; 

[request setURL:[NSURL URLWithString:@"http://localhost:8888/update.php"]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; 
[request setHTTPBody:postData]; 

我想問:

什麼是PHP腳本要收到請求數據,我怎麼能JSON數據進行解碼,以PHP對象更新數據庫?

任何幫助,將不勝感激。

回答

0

你會發現在變量$ _ POST [「JSON」],您可以通過使用看一看您通過POST收到你的數據:

<?php print_r($_POST); ?> 

一旦你已經確定了是你的數據,你可以從使用JSON傳遞到PHP數據:

<?php $phpObj = json_decode($_POST['json']); ?> 

同樣,你可以使用的print_r來看看你的數據的結構:

<?php print_r($phpObj); ?> 
+0

謝謝你,我確實像你說的那樣,它完美地工作。 – haisergeant 2010-09-08 02:34:11

1

我沒有與iPhone做到了這一點,但看起來像它將是:

if(isset($_REQUEST['json']) && $_REQUEST['json']) { 
    $jsonObj = json_decode($_REQUEST['json']); 
    //mandatory sanitizing and verification here 
    //PDO examples 
    //$stmt = $db->prepare('INSERT ...'); 
    //$stmt->execute(array($jsonObj->userId, $jsonObj->specialData)); 
    //check statement execution 
} 

更多信息:

http://php.net/json_decode

http://php.net/pdo

1

下面是一些線代碼與您提供的有限信息

<?php 
// get data 
$rawJsonData = $_POST; 
$decodedData = json_decode($rawJsonData); 

// .. do some parsing on $decodedData .. 

// save data 
$db = new Db(); 
$db->insert('table', $decodedData); 

$decodedData將是一個PHP數組,您可以使用任何您需要的方式進行處理,然後保存到數據庫中。