1

我有这个代码:

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

4 回答 4

4

我建议,虽然未经测试:

$.ajax({
      type: "get",
      url: "/123",
      data: serializeData !== undefined ? formSerializedData : null,
      success: function(data){
        //......
      }
});
于 2013-03-02T15:24:50.887 回答
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));
}
于 2013-03-02T15:26:45.483 回答
1

我建议使用 ajaxSetUp :

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

   //Check for serializeData data and pass accordingly
  $.ajax({ data: myData });
于 2013-03-02T15:30:49.520 回答
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);
于 2013-03-02T15:45:57.093 回答