2014-02-17 36 views
0

我希望將一些數據發送到PHP文件,我得到的迴應是{"status":"error","code":-1,"original_request":null}後JSON到PHP服務器

我的目標C代碼:

NSMutableDictionary *questionDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:questionTitleString, @"question_title", questionBodyString, @"question_body", nil]; 


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://myURL/post.php"]]; 
[request setHTTPMethod:@"POST"]; 


NSData *jsonData = [NSJSONSerialization dataWithJSONObject:questionDictionary options:kNilOptions error:nil]; 

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

[request setValue:@"json" forHTTPHeaderField:@"Data-Type"]; 
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"]; 
[request setHTTPBody: jsonData]; 

NSURLConnection *postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; 

現在我的PHP代碼:

$postdata = file_get_contents("php://input"); 
$obj = json_decode($postdata); 

if (is_array($post_data)) 
    $response = array("status" => "ok", "code" => 0, "original request" => $post_data); 
else 
    $response = array("status" => "error", "code" => -1, "original_request" => $obj); 

$processed = json_encode($response); 
echo $processed; 

問題是PHP從我的應用程序收到請求,但沒有收到我發送給它的內容。

+1

不應該是is_array($ obj)而不是is_array($ post_data)?並且還「original_request」=> $ obj –

+2

也我猜json_decode需要第二個真正的參數依次解碼爲數組 –

回答

3

爲什麼在使用php://直接輸入json_decode()時有多個參數?

試試這個:

// See the underlying structure of your data; attempt to decode the JSON: 
var_dump($_POST); 

$data = json_decode($_POST['question_title'], true); 
var_dump($data); 

$data = json_decode($_POST['question_body'], true); 
var_dump($data); 

PHP爲我們提供了$_POST超全局一個很好的理由。另外,json_decode($string, true)將返回一個關聯數組。