簡體   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