jQuery数据中的动态POST键

时间:2012-01-25 10:16:02

标签: jquery

var type = $(this).attr("data-type");
var typeId = $(this).attr("data-value");

if(type=="category") var typeVar="cat";
else if(type=="subcategory") var typeVar="subcat";

$.ajax({
    url: 'admin-catalog/next',
    type: 'POST',
    dataType: 'json',
    data: {typeVar: typeId, limit: 9},
    success: newGalleryProducts
});

我的'data'键中的键'typeVar'需要是动态的,即它不应该发布'typeVar'作为键,它应该发布'cat'或'subcat'。

有人知道怎么做吗?

2 个答案:

答案 0 :(得分:3)

var type = $(this).attr("data-type");
var typeId = $(this).attr("data-value");

if(type=="category") var typeVar="cat";
else if(type=="subcategory") var typeVar="subcat";

var post_data = {};
post_data[typeVar] = typeId;
post_data['limit'] = 9;

$.ajax({
    url: 'admin-catalog/next',
    type: 'POST',
    dataType: 'json',
    data: post_data,
    success: newGalleryProducts
});

如果您想在data键中执行此操作,可以这样做:

data: function(){var o = {}; o[typeVar] = typeId; o['limit'] = 9;return o;}(),

或者像@archil一样,请使用JSON.parse方法:

data: JSON.parse('{ "' + typeVar + '": "' + typeId + '", "limit": "9"}'),

答案 1 :(得分:1)

使用JSON.parse

可以实现这一目标
$.ajax({
    url: 'admin-catalog/next',
    type: 'POST',
    dataType: 'json',
    data: JSON.Parse('{ "' + typeVar + '": "' + typeId + '", "limit": "9"}'),
    success: newGalleryProducts
});