将JSON转换为Array并获取类型

时间:2011-09-20 18:00:13

标签: php jquery ajax post

我有两个问题。

  1. 如何让我的脚本在javascript中警告变量type 而不是[object object]
  2. 如何在不返回的情况下让我的Json成功转换为数组 NULL
  3. 使用Javascript:

    $(document).ready(function() {
    
    // Arrays
    var title = $('.table-item-1 > strong').map(function () {
        var value = $(this).text();
            return value;
        }).get();
    
    var name = $('[width|="23%"]').next('.table-item-1').map(function () {
        var value = $(this).text();
            return value;
        }).get();
    
    var phone = $('[width|="23%"]').next('.table-item-1').next('.table-item-1').map(function () {
        var value = $(this).text();
            return value;
        }).get();
    
    var fax = $('[width|="23%"]').next('.table-item-1').next('.table-item-1').next('.table-item-1').map(function () {
        var value = $(this).text();
            return value;
        }).get();
    
    var email = $('[width|="23%"]').next('.table-item-1').next('.table-item-1').next('.table-item-1').next('.table-item-1 , a').map(function () {
        var value = $(this).text();
            return value;
        }).get();
    
    // Individual    
    var brand = $('.panel-1 tr strong').html();
    var corp = $('.panel-1 tr td :gt(0)').html();
    var web = $('.panel-1 tr td ~ .focus :not(strong)').html();
    var lna_code = $('.panel-1 tr td :last').html();
    var lna_class = $('.panel-1 tr td :gt(4)').html();
    
    
    var items = {
        'brand': brand,
        'corp': corp,
        'web': web,
        'lna_code': lna_code,
        'lna_class': lna_class,
        'title': title,
        'names': 
            name,
        'phones': 
            phone,
        'faxes': 
            fax,
        'emails': 
            email,
    };
    
    var data = $.toJSON(items);
    
    $.ajax({
        type: 'POST',
        url: 'http://xxxxxx.com/xxxxx/PHP/excel.php',
        data: {'data':data},
        success: function(data) {
            alert('success');
        },
        complete: function(data){
            alert(data); // alerts [object object] , want a string
       }
    });
    
    });
    

    PHP:

    <?php
    $json = $_POST['data'];
    $result = json_decode($json);
    $resultsType = gettype($result);
    echo $resultsType;
    ?>
    

    注意:我正在使用json.js进行$.toJSON(items);调用

1 个答案:

答案 0 :(得分:1)

如果你想让结果成为PHP方面的一个数组,它应该是javascript端的一个数组:

[value1]

而不是

{key1 = value1}

您的代码中发生的是您正在创建一个对象。该对象可能是你真正想要的,但是因为它似乎不必迭代PHP端的值,这将是实际数组而不是对象的唯一原因。

如果您按原样保留代码,则可以访问PHP端的值,如下所示:

echo $result->brand;