繁体   English   中英

通过POST进行数组(Ajax)

[英]Array via POST (Ajax)

好的,这似乎是最直接的方法,但是我真的不知道为什么要这样做,也找不到其他人遇到这个问题。

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

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

在数据对象中是一个称为items的数组。 当我记录数据对象时,就像应该的那样,它很好,但是当我在Express函数中记录数据对象时, items数组无缘无故地变为items[]

的NodeJS

'items[]': '15716345'

JS(浏览器)

items: [15716345]

知道这里发生了什么吗?

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

// 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
    });
  }
});

设置JSON主体解析器中间件 ,以获取对您的expressJS应用程序的请求。

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

app.use(bodyParser.json())

然后在AJAX请求中,将contentType设置为application/json而不是application/x-www-form-urlencoded; charset=UTF-8'的默认值application/x-www-form-urlencoded; charset=UTF-8' 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');
  }
});

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

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);
  }
});

暂无
暂无

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

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