通过jQuery Ajax发送Json数组

我将通过jquery ajax调用发送一个json对象数组到一个php文件。

var arr = new Array(); var record1 = {'a':'1','b':'2','c':'3'}; var record2 = {'d':'4','e':'5','f':'6'}; arr.push(record1); arr.push(record2); 

如何通过jquery ajax发送数组? 我怎样才能在php中获取值? 谢谢。

 $.ajax({ url: "api", type: "POST", dataType: 'json', data: JSON.stringify(arr), success: function(response){} }); 

并使用PHP:

 $strRequest = file_get_contents('php://input'); $Request = json_decode($strRequest); 

我认为JSON.stringify()可能很有用。

或者,您可以在php文件中使用json_decode()

首先下载并添加插件:jquery.json-2.4.js到您的项目。 这个插件提供了很多帮助你生活的助手。

然后在你的$ .ajax中,使用数据:$ .toJSON(arr),

您必须要知道的第一件事是,您需要使用两个文件才能让自己变得简单。 1.你要把你的PHP代码放在哪里phpcode.php 2.你要把你的ajax代码放在哪里ajax.html在你要放置你的ajax代码的页面中确保你连接到jquery插件然后

     
In your php page you need something like this at the end of your code // The JSON standard MIME header. header('Content-type: application/json'); echo json_encode($array); Note: I took an example from my working codes just to save the time but I think you get the Idea