2013-06-01 19 views
2

我第一次發送JSON到服務器,我不知道爲什麼我的PHP腳本沒有收到呼叫。從AFNetworking在PHP中恢復JSON

我認爲問題在於我如何從應用程序設置POST變量,我抓錯了一個或沒有按照預期設置$_POST['search']

任何人都可以指出我怎麼才能發佈數據,以及如何設置$_POST['search']正確

$var0當我從Xcode的輸出看它。

PHP

header('Content-Type: text/json'); 
$var = (isset($_POST['search']) ? json_decode($_POST['search']) : false); 
echo json_encode($var) 

Objective-C的

NSDictionary *[email protected]{@"userID": @"1", 
          @"search":@{@"for":@"routine", 
             @"page":@"1", 
             @"orderBy":@"new", 
             @"type":@"1"} 
          }; 
    NSURL *url = [[NSURL alloc]initWithString:@"http://192.168.1.64/"]; 
     AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url]; 
     httpClient.parameterEncoding = AFJSONParameterEncoding; 
     NSDictionary *params = myJson; 
     NSURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"http://192.168.1.64/igym/bootstrap.php" parameters:params]; 

     AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
                          success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){ 
                           NSLog(@"Inside the success block %@",JSON); 
                          } 
                          failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){ 
                           NSLog(@"json text is: %@", JSON); 
                           NSLog(@"Request failed with error: %@, %@", error, error.userInfo); 
                          }]; 
     [operation start]; 
+0

你試過使用'$ _GET'嗎? – Undo

+0

我應該將它作爲POST發送。得到的結果相同 –

回答

3

的問題是,你作爲JSON編碼的所有參數(包括 「搜索」):

httpClient.parameterEncoding = AFJSONParameterEncoding; 

所以,你不能在PHP訪問它使用

$_POST['search']; 

的數據是通過崗位在這種情況下,不發送

你可以做兩件事情:

  • 編碼只作爲JSON的檢索字典的內容(而不是所有參數)
  • 訪問的數據通過:

$post = json_decode(file_get_contents('php://input')); 

$崗位將包含所有發佈的數據json編碼是這樣的:

{ 
    search =  { 
     for = routine; 
     orderBy = new; 
     page = 1; 
     type = 1; 
    }; 
    userID = 1; 
} 
+0

我採取了httpClient.parameterEncoding = AFJSONParameterEncoding;現在它就像一個魅力。謝謝! :) –

0

這個問題可能是在這裏:

path:@"http://192.168.1.64/igym/bootstrap.php" 

您已經指定客戶端的基本URL,所以你不必把它放在路徑字符串中。嘗試用以下替換此代碼:

path:@"igym/bootstrap.php" 

除了這一點,其他問題是你可以發佈您的PARAMS的方式。你應該像這樣發送它們:

NSString *jsonParam = @"{\"userID\": \"1\", 
          \"search\":{\"for\":\"routine\", 
             \"page\":\"1\", 
             \"orderBy\":\"new\", 
             \"type\":\"1\"} 
          }"; 
NSDictionary *params = [NSDictionary dictionaryWithObject:jsonParam forKey:@"search"]; 

你的param在PHP腳本中被命名爲「search」,它的值是一個JSON字符串。

請注意我正在使用反斜槓在NSString中轉義引號。

+0

Aame結果我得到0.此外,示例字符串是錯誤的...首先,你不需要scape ....只是使用'「a」:「b」'...第二。 ..您將搜索參數(如userID)設爲搜索。你在做什麼,就像我做的一樣...... –