首页 > 解决方案 > 根据 if 条件在 $.ajax 中传递多个数据

问题描述

我想为角色编号 7 传递 4 个参数,为其他角色传递 3 个参数。现在在 if 条件中出现错误。如何在 if 条件下传递多个数据

未捕获的语法错误:意外的令牌 ==

$.ajax({
                    url: 'bulkUpdate',
                    type: 'get',
                    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    if(role==7){
                    data: {
                        'ids'  : join_selected_values,
                        'role' :role,
                        'prices':selected_price,
                        'currency':selected_currency
                    },
                    }
                    else{
                    data: {
                        'ids'  : join_selected_values,
                        'role' :role,
                        'comment':comment
                    },  
                    }
                    success: function (data) {
                    console.log('success');
                    },
                    }); 

标签: jqueryhtml

解决方案


那是因为您提供的语法不正确。data如果 AJAX 请求,只需在外部构建对象:

var ajaxData = {
    ids: join_selected_values,
    role: role
};

if (role === 7) {
    ajaxData['prices'] = selected_price;
    ajaxData['currency'] = selected_currency;
} else {
    ajaxData['comment'] = comment;
}

$.ajax({
    url: 'bulkUpdate',
    type: 'get',
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    data: ajaxData,
    success: function(data) {
        console.log('success');
    },
})

推荐阅读