简体   繁体   中英

How can I make ajax parameters dynamic?

Here is a part of my code:

if ( external_link ) {
   data = {external_link : external_link};
} else {
   data = form_data;
}

$.ajax({
    url: base_url + frm.attr('action'),
    type: frm.attr('method'),
    data: data,
    cache: false,
    contentType: false, // this
    processData: false, // and this should be removed when external_link isn't false 
    success: function (imageUpload) {

All I'm trying to do is making contentType: false and processData: false parameters dynamic. I mean, if the condition above was true, then those two mentioned parameters should be removed. How can I do that?

var ajaxParams = {
  url: base_url + frm.attr('action'),
  data: data
  // contentType not here
};

if (something) {
  ajaxParams.contentType = false; // add new parameter
}

$.ajax(ajaxParams);

Pass an object into ajax call instead creating a literal object there? Preferably by wrapping a function around the call.

Code below is not direct implementation but showcase of principle:

var makeAjaxAndExecute = function(param1, param2){
  var ajaxObjectInitiate = {object literal here}
  ajaxObjectInitiate.param1 = param1;
  ajaxObjectInitiate.param2 = param2;

  $.ajax(ajaxObjectInitiate //.... rest of your code 
}

You can further separate configuring the object and actually making the call, you can have general generator of requests elsewhere totally depends what are your needs and how complex do you wanna / need it to be.

If you need to do it on a lot of calls, I would opt for totally isolated builder that holds onto object and has getters and setters for options and possibly internal states and logic. And once object is set simple pass it to ajax call.

Scale-able, maintainable and easy to debug but not needed if you have simple logic as this.

What about defining the minimum set of options first, and add the other two if the condition is met?

var options = {
    url: base_url + frm.attr('action'),
    type: frm.attr('method'),
    data: data,
    cache: false,
    success: function (imageUpload) {
    ...
};

if ( external_link ) { // the external link entered

    options.contentType: false; // this
    options.processData: false; // and this should be removed when external_link isn't false 
    options.data = {external_link : external_link};
} else {
   options.data = form_data;
}

$.ajax(options);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM