2015-07-04 146 views
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; 

遠程服務器沒有適當的反應,而且似乎沒有得到正確編碼的數據。有人可以幫我解決這個問題嗎?

謝謝!

+0

在jQuery代碼的'data'參數裏面'data'只是一個字符串(看起來像JSON),而在你的PHP代碼它是一個對象。也許嘗試調整。 – Sirko

+0

感謝您的支持。我試過了你的建議,但還是不行。 –

回答

0

這個工作對我來說:

<?php 

    /* You need to define that parameter separately, 
    * as it is supposed to be passed as a JSON String. 
    */ 
    $data_field = array(
     'TrackPackagesRequest' => array(
      'appType' => 'WTRK', 
      'uniqueKey' => '', 
      'processingParameters' => (Object)array(), // Will be stringified as {} 
      'trackingInfoList' => array(
       array(
        'trackNumberInfo' => array(
         'trackingNumber' => '780909642310', 
         'trackingQualifier' => '', 
         'trackingCarrier' => '' 
        ) 
       ) 
      ) 
     ) 
    ); 

    $data = array(
     "action" => "trackpackages", 
     'format' => 'json', 
     'locale' => 'it_IT', 
     'version' => '1', 
     "data" => json_encode($data_field) // Insert the String 
    ); 

    $ch = curl_init('http://www.fedex.com/trackingCal/track'); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    // http_build_query will convert your parameters to param1=val1&param2=val2... 
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

    $result = curl_exec($ch); 
    echo $result; 

?> 
+0

謝謝Blex,您的解決方案就像一個魅力! –