【问题标题】:Array via POST (Ajax)通过 POST (Ajax) 的数组
【发布时间】:2019-10-28 16:54:50
【问题描述】:

好吧,这似乎是最直接的事情,但我真的不知道为什么会这样,也找不到其他人有这个问题。

这是我的问题,我正在发送这样的 POST 请求;

  $.ajax({
      type: "POST",
      url: '/user/sell',
      data: data,
      success: function(data) {
        console.log('Call was successful');
      }
    });

数据对象中有一个名为items 的数组。当我记录数据对象时它很好,就像它应该的那样,但是当我在我的快速函数中记录数据对象时,items 数组无缘无故地更改为items[]..

NodeJS

'items[]': '15716345'

JS(浏览器)

items: [15716345]

知道这里发生了什么吗?

以下是代码的完整版本。 整个区块(前端) // 验证地址 if($('.block.payment .wrapper 输入:eq(0)').val() !== $('.block.payment .wrapper 输入:eq(1)').val()){ return error('字段不匹配'); }

// Get known data
var type = $('.body.inventory .methods .method.selected').data('type'),
    items = [];

var data = {
  type,
  address: $('.block.payment .wrapper input:eq(0)').val()
}

if(type === 'steam'){
  var app = $('.body.inventory .sub-methods .method.selected').data('app');
  data['app'] = app;

  $('.body.inventory .item[data-app="'+app+'"].selected').each(function(){
    items.push($(this).data('id'));
  });
}else{
  $('.body.inventory .item[data-type="'+type+'"].selected').each(function(){
    items.push($(this).data('id'));
  });
}

data['items'] = items;

// Execute route or smt
$.ajax({
  type: "POST",
  url: '/user/sell',
  data: data,
  success: function(data) {
    console.log('Call was successful');
  }
});

后端

router.post('/sell', function(req, res, next) {
  try {
    console.log(req.body);
    res.send({
      success: 1
    });
  } catch(e) {
    if(e) console.log(e);

    res.send({
      success: 0,
      error: e
    });
  }
});

【问题讨论】:

  • 请提供 NodeJS 和 JS 代码以便更好地理解。
  • 您在使用任何logger 库吗?在节点侧
  • 您提供的数据似乎来自一个表单,在该表单中,您使用 [] 语法和多个输入将它们转换为数组。你在使用 FormData 吗?
  • 对不起,我会添加更多代码..
  • 这似乎使用了特定于表单数据的原始 bodyParser 中间件,而不是 expressJS 中的 json bodyParser expressjs.com/en/resources/middleware/…

标签: javascript jquery arrays node.js express


【解决方案1】:

为您的 expressJS 应用程序的请求设置 JSON body parser middleware

const bodyParser = require('body-parser');

app.use(bodyParser.json())

在 AJAX 请求中,将 contentType 设为 application/json 而不是默认的 application/x-www-form-urlencoded; charset=UTF-8'

$.ajax({
  contentType: 'application/json',
  type: "POST",
  url: '/user/sell',
  data: data,
  success: function(data) {
    console.log('Call was successful');
  }
});

【讨论】:

  • 是的,它应该包装 body-parser API。唯一缺少的可能是您发送的 AJAX 请求中的内容类型。
  • 是的,我添加了它,但似乎仍然有相同的结果。
  • 我决定将数组作为字符串发送过来,然后将其解码回服务器端的数组,这样可以正常工作。不确定这是否是最好的做法,但它会起作用。
【解决方案2】:

假设这是您要发布的数组列表。

object[] Obj = new object[1];
Obj [0] = "value1"
Obj [1] = "Value2"
Obj [3] = {"CollectionValue1, CollectionValue2"}

$.ajax({
  url: '../Controller/MethodName',
  type: 'post',
  datatype: 'json',
  async: false,
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify({ ControllerParameterName: Obj }), <!-- Obj is your Array -->
  success: function (data) {
    alert(data.Response);
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多