简体   繁体   English

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

[英]Can I send an array by jquery.getJSON?

I have this jquery code: 我有这个jQuery代码:

$(".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代码-addToSession.php(仅用于测试其是否有效,最终代码将有所不同):

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

It doesn't work. 没用 Nothing comes back. 什么也没回来。 My question is, can I send an array of objects to $.getJSON? 我的问题是,我可以将对象数组发送到$ .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. 如果可以的话,它不必是对象数组,也可以是数组数组。

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). 它不会在console.log中显示,因为getJSON要求它得到的响应是JSON,并且您正在响应的内容声称是HTML文档(PHP的默认设置),但包含print_r的输出(不是有效的HTML或JSON)。

Send JSON back and it will work: 发送回JSON,它将起作用:

<?php
    header("Content-Type: application/json");
    echo json_encode($_GET['sendArray']);
?>

In this case you should use http://api.jquery.com/jQuery.post/ instead. 在这种情况下,您应该改用http://api.jquery.com/jQuery.post/

JQuery.getJSON, as name of method says should be used to GET JSON data, and not send it. 顾名思义,JQuery.getJSON应该用于获取JSON数据,而不是发送它。 Thats because your array is converted to GET, and it generate json request like 那是因为您的数组已转换为GET,并且它会生成json请求,例如

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

To send JSON data use jQuery.post with "json" dataType. 要发送JSON数据,请使用jQuery.post和“ json”数据类型。

$.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'}
]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM