2014-03-26 52 views
0

我想實現的目標:使用HTML/JQUERY並將XMLHttpRequest(JSON)發佈到php文件中,然後我們可以使用CURL將json提交到外部網站。將JSON發佈到php然後捲曲到不同的域

這裏是我提交該數據的方式:

var myDate = "30/01/2014"; 
var n=myDate.split("/"); 
var fdate = (n[2]+"-"+n[1]+"-"+n[0]); 

var xhr = new XMLHttpRequest(); 
xhr.open("POST", "index.php"); 
xhr.setRequestHeader("Content-Type", "application/json"); 
xhr.onreadystatechange = function() { 
    if (this.readyState == 4) { 
    alert('Status: '+this.status+'\nHeaders: '+JSON.stringify(this.getAllResponseHeaders())+'\nBody: '+this.responseText); 
    } 
}; 
xhr.send("{\n \"utoken\": \"\",,\n \"email\": \"[email protected]\",\n \"customer_name\": \"blah blah\",\n \"order_id\": \"112897\",\n \"platform\": \"general\",\n \"order_date\": \"" + fdate + "\",\n \"currency_iso\": \"GBP\"\n}"); 

現在我怎樣才能在PHP中的這些數據,並對其進行操作。因爲有一些像utoken,我可以從PHP文件中獲得,但無法獲得其他信息。

PHP

$chs = curl_init(); 
curl_setopt($chs, CURLOPT_URL, "EXTERNAL API URL"); 
curl_setopt($chs, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($chs, CURLOPT_HEADER, FALSE); 
curl_setopt($chs, CURLOPT_POST, TRUE); 
curl_setopt($chs, CURLOPT_POSTFIELDS, print_r($HTTP_RAW_POST_DATA);); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); 
$response = curl_exec($chs); 
curl_close($chs); 
+0

你熟悉'在PHP json_decode'? – skywalker

回答

0

你應該格式化你要發送這樣的數據:

xhr.send("utoken=&[email protected]&customer_name=blah blah&order_id=112897&platform=general&order_date=" + fdate + "&currency_iso=GBP"); 

以下行將不工作,要麼作爲print_r的打印出數組。你也有一個語法錯誤(;在函數參數裏面)。

curl_setopt($chs, CURLOPT_POSTFIELDS, print_r($HTTP_RAW_POST_DATA);); 

而是嘗試:

curl_setopt($chs, CURLOPT_POSTFIELDS, $HTTP_RAW_POST_DATA); 

希望幫助

0

既然你發佈JSON,您的POST請求應該有如下:

curl_setopt($chs, CURLOPT_POSTFIELDS, '{"utoken":"", "email":"[email protected]"}'); 

或者,如果你有一個像下面這樣的數組,那麼你可以使用json_encode來使你的數組​​變成json輕鬆的帖子。

$post_data = array(
    "utoken" => "", 
    "email" => "[email protected]" 
); 
curl_setopt($chs, CURLOPT_POSTFIELDS, json_encode($post_data)); 

供參考:功能json_encode轉換數組值到{"utoken":"","email":"[email protected]"}