如果条件为真,则向哈希添加密钥

时间:2013-03-02 15:19:53

标签: javascript

我有这段代码:

function myFunction(serializeData, extraSerializedData){
  //serializeData is boolean
  var    formSerializedData = '';
  if(serializeData){
      var formSerializedData = $("#myform").serialize();
      if (typeof extraSerializedData !== 'undefined'){
        formSerializedData += extraSerializedData;
      }
    }

    $.ajax({
      type: "get",
      url: "/123",
      data: formSerializedData, //TODO!!!       
      success: function(data){
        //......

我只想在data存在的情况下添加serializeData密钥。是否有可能以及如何以代码保持“漂亮”的方式执行此操作?

4 个答案:

答案 0 :(得分:4)

我建议,虽然未经测试:

$.ajax({
      type: "get",
      url: "/123",
      data: serializeData !== undefined ? formSerializedData : null,
      success: function(data){
        //......
      }
});

答案 1 :(得分:1)

我讨厌三元运算符,所以在这里有这个:

function myFunction(serializeData, extraSerializedData){
    var formSerializedData = '';
    var extendWith = {};

    if(serializeData){
        var formSerializedData = $("#myform").serialize();
        if (typeof extraSerializedData !== 'undefined'){
            formSerializedData += extraSerializedData;
        }
        extendWith.data = formSerializedData;
    }

    $.ajax($.extend({
        type: "get",
        url: "/123",    
        success: function(data){
            //......
        }
        //rest of the object
    },extendWith));
}

答案 2 :(得分:1)

我建议使用ajaxSetUp:

 $.ajaxSetup({
     url: "/123/",
     type: "get",
     success: function(){};
   });

   //Check for serializeData data and pass accordingly
  $.ajax({ data: myData });

答案 3 :(得分:1)

function myFunction(serializeData, extraSerializedData){
    var ajaxthing = {
        type: 'get', 
        url: '/123', 
        success: function (data) {...}
    };

    if(serializeData){
        var formSerializedData = $("#myform").serialize();
        if (typeof extraSerializedData !== 'undefined'){
            formSerializedData += extraSerializedData;
        }
        ajaxthing.data = formSerializedData;
    }

    $.ajax(ajaxthing);