【问题标题】:How to get correct return an array for ajax?如何获得正确的ajax返回数组?
【发布时间】:2014-09-05 16:04:54
【问题描述】:

我正在使用 api dataTable 和 ajax。

我生成一个这样的数组:

[['1','2','3'],['4','5','6']]

在我从 ajax 返回时,在 dataTable 中不起作用,但如果我复制这个数组并放入:

success: function (result) {
    result = [['1','2','3'],['4','5','6']];
}

示例脚本:

jQuery.ajax({
                url: "<?php echo Mage::getSingleton('adminhtml/url')->getUrl('pagseguro/adminhtml_ajax'); ?>",
                type: "POST",
                data: { 
                        form_key: "<?php echo Mage::getSingleton('core/session')->getFormKey();?>", 
                        days: getDays
                        },
                success: function(result) {
                    if (result != "") {
                        jQuery('#htmlgrid').dataTable().fnClearTable(true);           
                        jQuery('#htmlgrid').dataTable().fnAddData(result);
                        //jQuery('#htmlgrid').dataTable().fnStandingRedraw();
                    }

                    blockModal(0);
                },
                error: function() {
                    blockModal(0);
                }
            });

作品,已经尝试了几十种方式以json数组返回,不知道为什么要返回,php不能与物理放置在脚本作品中的数组一起工作。

示例 1 php:

print_r($array) = array ([0] => Array ( [date] => 15/07/2014 [id_magento] => #100000031 [status_magento] => Pendente) 
   [1] => Array ( [date] => 15/07/2014 [id_magento] => #100000030 [status_magento] => Pendente))

处理$array代码:

foreach ($array as $info) {

                $i = 1;
                $dataSet .= ($j > 1) ? ",[" : "[";              

                foreach ($info as $item) {

                    $dataSet .= (count($info) != $i) ? "'" . $item . "'," : "'" . $item . "'";          
                    $i++;   

                }

                $dataSet .= "]";
                $j++;

            }

            $dataSet .= "]";
            echo $dataSet;

示例 2 php:

echo json_encode($array);

【问题讨论】:

  • 向我们展示如何生成 JSON 数组并将其发送到浏览器的代码。
  • 哎呀...如果您有像json_encode($array); 这样的函数供您使用,为什么有人会手动(而且很糟糕)尝试生成 JSON 字符串?

标签: php ajax arrays json datatable


【解决方案1】:
$.ajax({
    url: '',
    type: 'GET',
    dataType: 'JSON',
    data: {

    }
    success: function(aData) {
         console.log(aData);
    }
});

您的ajax request 中缺少DataType。

应该帮助或尝试 $.parseJSON(yourJsonString)

【讨论】:

    【解决方案2】:

    根据您发布的代码。有一个 PHP 函数和一个 HTTP 标头,您应该阅读它们。

    所以你最终会得到类似的东西

    // Tell browser it'll receive JSON data
    header('Content-Type: application/json'); 
    
    // Parses your array as a valid JSON string
    echo json_encode($array); 
    

    【讨论】:

    • 这只是一个概念。根据您的具体情况进行调整。
    • 显然有效,但不返回表中的数据,仅创建 trd 而没有给出 tds
    • 如果您的 ajax 请求现在从服务器接收到有效且可用的 json 数据,这个问题就解决了。如果客户端站点上的其他内容不起作用。为此打开一个新问题。
    猜你喜欢
    • 2023-03-11
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 2011-04-02
    • 2023-02-22
    相关资源
    最近更新 更多