所以我有一个对象
var ajaxOptions = {
url: ajaxurl,
type: 'POST',
async: false,
success: function (retval) {
if (!JSON.parse(retval))
{
alert("Error occurred.");
}
else
{
jQuery('#member-modal').modal('hide');
location.reload();
}
},
cache: false,
contentType: false,
processData: false
};
我想在我的几段代码中重用,比如
var theseOptions = ajaxOptions;
theseOptions.data = new FormData($('#thisform')[0]);
$.ajax(theseOptions);
// ... somewhere else in code ...
var thoseOptions = ajaxOptions;
thoseOptions.data = new FormData($('#thatform')[0]);
thoseOptions.someOtherOption = "hehehe";
$.ajax(thoseOptions);
// ... somewhere else in code ...
var poopOptions = ajaxOptions;
poopOptions.data = new FormData($('#poopform')[0]);
$.ajax(poopOptions);
问题是,据我所知,我的var
实际上是对现有ajaxOptions
的引用,例如,当我运行
$.ajax(poopOptions);
键值对someOtherOptions : "hehehe"
仍然存在。实际上我必须做类似
var theseOptions = ajaxOptions;
theseOptions.data = new FormData($('#thisform')[0]);
$.ajax(theseOptions);
delete thoseOptions.data; // now ajaxOptions is back to what it originally was
// ... somewhere else in code ...
var thoseOptions = ajaxOptions;
theseOptions.data = new FormData($('#thatform')[0]);
theseOptions.someOtherOption = "hehehe";
$.ajax(thoseOptions);
delete thoseOptions.data; delete thoseOptions.someOtherOption; // // now ajaxOptions is back to what it originally was
// ... somewhere else in code ...
var poopOptions = ajaxOptions;
poopOptions.data = new FormData($('#poopform')[0]);
$.ajax(poopOptions);
delete poopOptions.data; // now ajaxOptions is back to what it originally was
或者我可能需要做类似
的事情function getAjaxBaseOptions ( )
{
return {
url: ajaxurl,
type: 'POST',
async: false,
success: function (retval) {
if (!JSON.parse(retval))
{
alert("Error occurred.");
}
else
{
jQuery('#member-modal').modal('hide');
location.reload();
}
},
cache: false,
contentType: false,
processData: false
};
}
var theseOptions = getAjaxBaseOptions();
theseOptions.data = new FormData($('#thisform')[0]);
$.ajax(theseOptions);
// ... somewhere else in code ...
var thoseOptions = getAjaxBaseOptions();
thoseOptions.data = new FormData($('#thatform')[0]);
thoseOptions.someOtherOption = "hehehe";
$.ajax(thoseOptions);
// ... somewhere else in code ...
var poopOptions = getAjaxBaseOptions();
poopOptions.data = new FormData($('#poopform')[0]);
$.ajax(poopOptions);
这看起来有点荒谬。在Javascript中真的没有直接复制对象的原生方式吗? WTF?