【问题标题】:Need help formulating a correct JSON response需要帮助制定正确的 JSON 响应
【发布时间】:2014-05-26 16:49:55
【问题描述】:

我是使用 Jquery ajax 调用和 json 响应的新手,遇到了一个需要帮助克服的问题。

我正在使用cleeng open API,我想知道我正在使用的其中一个 api 调用的响应 - getRentalOffer()

我正在使用 jquery $ajax() 请求,我想进行 getRentalOffer() api 调用并以 JSON 格式返回结果。到目前为止,我的努力是这样的(假设 POST 请求以 id 作为参数。)

请求:

<script type="text/javascript">

    $(document).ready(function() {

        $( "#getOfferButton" ).click(function() {


            var offerId = document.frm.offerID.value;

            $.ajax({
                // the URL for the request
                url: "ajax-get-offer.php",

                // the data to send (will be converted to a query string)
                data: {
                    id: offerId
                },

                // whether this is a POST or GET request
                type: "POST",

                // the type of data we expect back
                dataType : "json",

                // code to run if the request succeeds;
                // the response is passed to the function
                success: function(json) {



                // $("#title").val = json.title;
                  /*
                   $.each(json, function(i, item){
                           $("#"+item.field).val(item.value);
                        }); 
                   */
                 console.log(json);

                },

                // code to run if the request fails; the raw request and
                // status codes are passed to the function
                error: function( xhr, status, errorThrown ) {
                    alert( "Sorry, there was a problem!" );
                    console.log( "Error: " + errorThrown );
                    console.log( "Status: " + status );
                    console.dir( xhr );
                },

                // code to run regardless of success or failure
                complete: function( xhr, status ) {
                    alert( "The request is complete!" );
                }
            });

        });
    });
    </script>

ajax-get-offer.php:

<?php
include_once('Cleeng-cleeng-php-sdk-fe2a543/cleeng_api.php');
/*
Using FirePHP to log variables
*/
require_once('FirePHPCore/FirePHP.class.php');
ob_start();
$firephp = FirePHP::getInstance(true);

$offerID = $_POST['id'];


$firephp->log($offerID, 'offerID');//For debugging

$publisherToken = 'My super secret token goes here!';
$cleengApi = new Cleeng_Api();
$cleengApi->setPublisherToken($publisherToken);
$offerDetails = $cleengApi->getRentalOffer($offerID);


$firephp->log($offerDetails, 'offerDetails');//For debugging

echo $offerDetails;
?>

当我尝试这个时,我得到内部服务器错误。我尝试使用 echo json_encode($offerDetails);在最后一个 echo 语句上,然后我没有收到服务器错误。然而,响应似乎只包含 JSON 对象的最后一个元素。

我需要帮助来了解如何处理来自 getRentalOffer() 的 API 响应,以便将其作为正确的 JSON 响应传递给 $ajax() 请求。

我希望我的问题有意义。 :-)

编辑:使用 print_r insead of echo 我确实收到了响应文本,但遗憾的是出现了错误。这是文本,在我看来好像需要在使用 print_r 之前正确格式化。

"Cleeng_Entity_RentalOffer Object ( [id:protected] => R875937249_SE [publisherEmail:protected] => martin.xxxxxxxx@xxxxxxx.se [url:protected] => http://xxx.xxxxxx.xx/cleeng_tool [title:protected] => Tjohooo! [description:protected] => En skön rulle om Afrika. [price:protected] => 55 [applicableTaxRate:protected] => 0.21 [period:protected] => 48 [currency:protected] => EUR [socialCommissionRate:protected] => 0 [contentType:protected] => video [contentExternalId:protected] => xxxxxxxxxxx [contentExternalData:protected] => {"platform":"vimeo","dimWidth":"500","dimHeight":"369","hasPreview":false,"previewVideoId":"","backgroundImage":"https://i.vimeocdn.com/video/xxxxxxxxx_960.jpg"} [contentAgeRestriction:protected] => [tags:protected] => Array ( [0] => abo ) [active:protected] => 1 [createdAt:protected] => 1400588711 [updatedAt:protected] => 1400606512 [pending:protected] => [averageRating] => 4 ) "

【问题讨论】:

  • 我真的需要一些帮助。 :-)
  • 使用echo json_encode($offerDetails)而不是echo $offerDetails是正确的选择
  • 我想在这里查看您的代码:$cleengApi-&gt;getRentalOffer() 我认为它只是通过了一行,而不是行。
  • 它确实通过了所有行,我用 FirePHP 检查了 $offerDetails 以确保。
  • 你能粘贴json_encoded 结果而不是print_r 吗?我真的很想看看你的getRentalOffer()函数。

标签: php jquery ajax json


【解决方案1】:

您无法回显数组或对象,请尝试使用

print_r($offerDetails);

var_dump($offerDetails);

【讨论】:

  • 我尝试了 print_r 并得到了这个错误:错误:SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符。我用响应文本编辑了 OP。
【解决方案2】:

解决了。

getRentalOffer() 返回的对象包含不会被 json_encode 编码的受保护成员,因为它尊重对象 vars 中的访问参数。我在这篇文章中找到了一个不错的解决方案:http://smorgasbork.com/component/content/article/34-web/65-json-encoding-private-class-members

这不是一个可靠的解决方案,因为它依赖于一个漏洞,有朝一日可能会被关闭,因此请注意这一点。但是对于我的需要就足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2021-06-26
    • 2014-01-29
    • 1970-01-01
    相关资源
    最近更新 更多