javascript - 如何 AJAX POST 对象数组到 Node.js 服务器?

标签 javascript arrays ajax node.js object

有没有办法可以 ajax 发布对象数组并在 Node.js 服务器上解析它?这是我的客户端代码:

var context = [];

obj1 = {
      first_name: 'e',
      last_name: 'e',
      contact_email: 'e',
      contact_phone_num: 'e',
      contact_notes: 'e' 
  }


  obj2 = {
      first_name: 'a',
      last_name: 'a',
      contact_email: 'a',
      contact_phone_num: 'a',
      contact_notes: 'a' 
  }


  var context = [];

  context.push(obj1);
  context.push(obj2)


  $.ajax({
    type: "POST",
    url: '/api/addcontact',
    data: context,
    success: function(data, status) {
        alert('company added!');

    },
    error: function(data, status, res) {
        console.log('err: ' + res);
    }
});

我的服务器端代码:

api.post('/api/addcompany', function(req, res) {
    console.log('add company hit');
    console.log(req.body);  //returns {}
    res.sendStatus(200);
});

现在,当我打印请求正文时,它会返回 {}

有人可以帮助我在服务器端正确访问对象数组吗?

提前致谢!

最佳答案

发生这种情况是因为您没有在ajax帖子中发送对象,而是发送数组。尝试将数组包装在 {} 中以表明它确实是一个对象,然后在服务器代码中引用该对象属性。

var context = []; // array

  context.push(obj1);
  context.push(obj2)


  $.ajax({
    type: "POST",
    url: '/api/addcontact',
    data: {context: context}, // requires an object here
    success: function(data, status) {
        alert('company added!');

    },
    error: function(data, status, res) {
        console.log('err: ' + res);
    }
});

然后在服务器端脚本中,您可以引用 body 对象的 context 属性。

关于javascript - 如何 AJAX POST 对象数组到 Node.js 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35807456/

相关文章:

php - 如何使用 AJAX 和 JSON 从一个页面抓取 PHP 变量到另一个页面?

javascript - WordPress自定义页面模板从子目录读取

java - 使用外部变量更改数组的内容

php - 将对象转换为数组 - 调用任何魔术方法?

javascript - 处理动态表格

php - 通过ajax将数组传递给php

Javascript/jQuery - 将值添加到整数会更改其他变量

javascript - 在页面加载时动画对象,但仍然能够随着悬停而改变

javascript - 如何使用 createTextNode 插入 HTML 实体?

Javascript Array Scope - 这里是新手