2014-10-10 99 views
1

我在swift ios中創建了一個HTTP POST請求。當我在php文件中獲取一個post變量時,它顯示爲空白,我沒有得到一個變量值。在我的swift代碼下面,看看它。獲取swift post變量時出錯

var dataString = "name=john&type=student" 

var request : NSMutableURLRequest = NSMutableURLRequest() 

request.URL = NSURL(string: "http://www.example.com/example.php") 

var postString = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding) 

request.HTTPMethod = "POST" 

request.setValue("application/json", forHTTPHeaderField: "Content-Type") 

request.HTTPBody = postString 

var connection = NSURLConnection(request: request, delegate: self, startImmediately: false) 

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { 
    //New request so we need to clear the data object 
    println(response) 
} 

PHP代碼:

<?php 
echo $_POST['name']; 
?> 

任何人都可以建議我應該得到一個變量的值做。由於

回答

0

您應該使用application/x-www-form-urlencoded代替application/json

+0

Content-Type實際上,它__does__回答這個問題。問題在於他以x-www-form-urlencoded格式將數據作爲主體發送,並將其稱爲JSON。由於他告訴PHP它是JSON,因此它不會被解碼爲POST參數到_POST。 – 2014-10-10 19:31:14

+0

現在它正在工作。謝謝@David – Viju 2014-10-11 05:35:46