JSON - 将代码从JQuery转换为PHP

时间:2015-07-04 12:04:07

标签: javascript php jquery json

我正在尝试将代码从JQuery转换为PHP,以便对远程服务器执行json POST请求。

我的Jquery代码是:

FileUtils.listFilesAndDirs(basePath, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)

我想从PHP做同样的POST请求调用,但我不能。

我的PHP代码是:

$( 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 );
            });
        }
    )
});

远程服务器没有正确响应,似乎没有收到正确编码的数据。有人可以帮我解决这个问题吗?

谢谢!

1 个答案:

答案 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;

?>