dongwei2030
dongwei2030
2014-07-09 08:00

我可以通过jquery.getJSON发送数组吗?

I have this jquery code:

$(".cashOutButton").click(function(e){
    e.preventDefault();
    var sendArray=[{'value': '123', 'type': 'Buy_Order_ID'},
                    {'value': '44.20', 'type': 'Set_Price'},
                    {'value': 'John', 'type': 'seller_Name'},
                    {'value': 'S', 'type': 'Sell_Type'}
                    ];

    var sendData = {'sendArray': sendArray};

    $.getJSON('addToSession.php',sendData,function(data){
        console.log(data);
    });        

})

and this php code - addToSession.php (it's just to test if it's working, the final code will be different):

<?php
print_r($_GET['sendArray']);
?>

It doesn't work. Nothing comes back. My question is, can I send an array of objects to $.getJSON? What other solutions are there to send arrays? It doesn't have to be array of objects, it could be array of arrays, if that would work.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douyou3619 douyou3619 7年前

    You can, and this is returning the data you expect. You can test this by looking at the response in the Net tab of your browser's developer tools.

    It isn't being displayed in console.log because getJSON requires that the response it gets is JSON and you are responding something that claims to be an HTML document (the default for PHP) but which contains the output of print_r (which isn't valid HTML or JSON).

    Send JSON back and it will work:

    <?php
        header("Content-Type: application/json");
        echo json_encode($_GET['sendArray']);
    ?>
    
    点赞 评论 复制链接分享
  • douyi3760 douyi3760 7年前

    In this case you should use http://api.jquery.com/jQuery.post/ instead.

    JQuery.getJSON, as name of method says should be used to GET JSON data, and not send it. Thats because your array is converted to GET, and it generate json request like

    addToSession.php?undefined=123&undefined=44.20&undefined=John&undefined=S.

    To send JSON data use jQuery.post with "json" dataType.

    $.post( "addToSession.php", sendData, function( data ) {
      console.log( data);
    }, "json");
    

    And your array should be in final like:

    {sendData: [ {'value': '123', 'type': 'Buy_Order_ID'},
             {'value': '44.20', 'type': 'Set_Price'},
             {'value': 'John', 'type': 'seller_Name'},
             {'value': 'S', 'type': 'Sell_Type'}
    ]}
    
    点赞 评论 复制链接分享