简体   繁体   English

将一组对象作为ajax发布数据发送?

[英]Sending an array of objects as ajax post data?

My overall goal is to get all some of all drop-downs on a page and send that to be processed by a php file. 我的总体目标是在页面上获取所有部分下拉菜单并将其发送给php文件进行处理。

Right now, the way I'm doing it in jQuery is making an overall schedule array and then adding each element to be updated to that array. 现在,我在jQuery中执行此操作的方式是创建一个整体调度数组,然后将要更新的每个元素添加到该数组中。 So I have something like: 所以我有类似的东西:

var schedule = [];
var data = { 
   'user_id' : '12', 
   'day_of_week' : 'Monday',
    'when' : 'start',
    'time' : '12 AM'
 }
schedule.push(data);
var data = { 
   'user_id' : '13', 
   'day_of_week' : 'Tuesday',
    'when' : 'end',
    'time' : '12 AM'
 }
schedule.push(data);
// schedule would have two objects in it

Obviously in loops and and stuff. 显然是循环和东西。

So, my schedule array has two objects in it, in this case. 因此,我的schedule数组中有两个对象,在本例中。

Now, is it possible to use that schedule array as the ajax data? 现在,是否可以将该计划数组用作ajax数据? It doesn't work if I do something like: 如果我执行以下操作,它将无效:

$.ajax({
  url: 'http://something.com/ajax',
  data: schedule,
  type: 'POST'
});

But if I instead change it to schedule[0] it works just fine, but only for the first thing in the schedule array, obviously. 但是,如果我将其更改为schedule[0]它可以正常工作,但显然只是对于schedule数组中的第一件事。

The data attribute should be an object. data属性应该是一个对象。

What you can do is this: 你能做的是:

$.ajax({
  url: 'http://something.com/ajax',
  data: {schedule: schedule},
  type: 'POST'
});

So if you receive this for example in PHP you have $_POST["schedule"] . 因此,如果你在PHP中收到这个,那你就有$_POST["schedule"] An that is exactly the same as you had in JavaScript. 这与JavaScript中的完全相同。

Ohh yes I've forgot... also have a look at .serialize() and .serializeArray() ! 哦,是的,我忘记了......还看看.serialize().serializeArray()

Make sure you are using the correct version of jQuery. 确保您使用的是正确版本的jQuery。 In earlier versions, you had to pass a sting; 在早期版本中,你必须通过一个刺痛; new versions use "intelligent guess" on the data variable. 新版本对data变量使用“智能猜测”。 You can either explicitly tell jQuery that you're passing it a javascript object with the dataType parameter, or you can let jQuery figure it out. 您可以明确告诉jQuery您使用dataType参数传递javascript对象,或者您可以让jQuery弄清楚它。

Documentation 文档

jQuery.ajax() - http://api.jquery.com/jQuery.ajax/ jQuery.ajax() - http://api.jquery.com/jQuery.ajax/

Pass it as JSON: 将其作为JSON传递:

$.ajax({
  url: 'http://something.com/ajax',
  data: {schedule: schedule},
  type: 'POST',
  dataType: 'JSON'
});

It would send a JSON encoded string to the server, which server-side languages can parse. 它会将一个JSON编码的字符串发送到服务器,服务器端语言可以解析。 (in PHP, it's done with json_decode() ). (在PHP中,它是用json_decode() )。

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

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