1
我試圖將代碼從JQuery轉換爲PHP來執行json POST請求到遠程服務器。JSON - 將代碼從JQuery轉換爲PHP
我jQuery代碼是:
$(document).ready(function() {
$('#button').click(
function() {
$.ajax({
method: "POST",
url: "http://http://www.fedex.com/trackingCal/track",
data: {
action: "trackpackages",
format: "json",
locale: "it_IT",
version: "1",
data: '{"TrackPackagesRequest":{"appType":"WTRK","uniqueKey":"","processingParameters":{},"trackingInfoList":[{"trackNumberInfo":{"trackingNumber":"780909642310","trackingQualifier":"","trackingCarrier":""}}]}}'
}
})
.done(function(msg) {
console.log(msg);
});
}
)
});
我想從PHP做相同的POST請求調用,但我不能。
我的PHP代碼:
$data = array("action" => "trackpackages", "data" => array ('TrackPackagesRequest' => array('appType' => 'WTRK', 'uniqueKey' => '', 'processingParameters' => '{}', 'trackingInfoList' => array(array('trackNumberInfo' => array('trackingNumber' => '780909642310', 'trackingQualifier' => '', 'trackingCarrier' => ''))))), 'format' => 'json', 'locale' => 'it_IT', 'version' => '1');
$data_string = json_encode($data);
$ch = curl_init('http://www.fedex.com/trackingCal/track');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
echo $result;
遠程服務器沒有適當的反應,而且似乎沒有得到正確編碼的數據。有人可以幫我解決這個問題嗎?
謝謝!
在jQuery代碼的'data'參數裏面'data'只是一個字符串(看起來像JSON),而在你的PHP代碼它是一個對象。也許嘗試調整。 – Sirko
感謝您的支持。我試過了你的建議,但還是不行。 –