如果条件为真,则在Ajax调用中添加参数

时间:2015-07-20 12:49:19

标签: javascript jquery ajax

这是我以前的代码:

$.ajax({
    type: "POST",
    url: "/Test/Save",
    data: {
        comments: $('#comments').val()
        <% if (SomeCondition) { %>,
            profit: parseInt(profitCombo.getSelectedValue())
        <% } %>,
        myData: JSON.stringify(someData).toString()
    }
...

现在,我将此代码放在一个单独的JS文件中,我需要删除ASPX调用。我有一个变量some​​ConditionJsVariable,所以我想做这样的事情:

data: {
        comments: $('#comments').val()
        if (someConditionJsVariable) {,
            profit: parseInt(profitCombo.getSelectedValue())
        },
        myData: JSON.stringify(someData).toString()
    }

如果该变量为true,则添加逗号和另一个参数。怎么做到这个?

3 个答案:

答案 0 :(得分:1)

使用函数

之前构建对象
$.ajax({
        type: "POST",
        url: "/Test/Save",
        data: getMyDataObject()
        //other settings
});

function getMyDataObject() {
  var myDataObject = {
   comments: $('#comments').val()
   myData: JSON.stringify(someData).toString()
  }

  if (someConditionJsVariable) {
            myDataObject.profit= parseInt(profitCombo.getSelectedValue());
  }
  return myDataObject;
}

答案 1 :(得分:1)

您可以将代码更新为以下

// create object
var data = {
        comments: $('#comments').val(),
        myData: JSON.stringify(someData).toString()
    }

if (someConditionJsVariable) {,
     data.profit = parseInt(profitCombo.getSelectedValue());
}

data : data // pass object

答案 2 :(得分:1)

您可以将所有逻辑包装成如下函数:

var testSave = function(someConditionJsVariable, someData, profitCombo) {

    // construct your data object
    var data = {
        comments: $('#comments').val(),
        myData: JSON.stringify(someData),
    }

    // assign the conditional property with value depending on condition
    !!someConditionJsVariable && (data.profit = parseInt(profitCombo.getSelectedValue()));

    // return the jQuery promise from ajax call
    return $.ajax({
        type: "POST",
        url: "/Test/Save",
        data: data
    });
}

然后使用这样的函数:

testSave(someConditionJsVariable, someData, profitCombo)
    .then(function(result) {
        // do something with result
    });