我遇到了一个问题,jQuery.ajax() 正在调用我的数据对象函数。例如,我有一个类似于下面的对象结构:
var TestFactory = (function () {
var _id;
var _attributes;
return {
createObject: function (objectId) {
var value = null;
_id = objectId;
_attributes = {};
function _showErrorStatus() {
$('label')
.css('background-color', 'red')
.css('color', 'black')
.text('jQuery called me...');
}
function _attr(key, value) {
if (value == null) {
return _attributes[key];
}
_attributes[key] = value;
return this;
}
return {
id: _id,
attributes: _attributes,
showErrorStatus: _showErrorStatus,
attr: _attr,
}
}
}
})();
我想使用这个对象作为我的 jQuery.ajax() 调用的数据值,如下所示:
var myObject = TestFactory.createObject(12345);
myObject.attr('name', 'Fred Flinstone');
$.ajax({
url: '/echo/json/',
type: 'GET',
data: myObject,
dataType: 'json',
});
我遇到的问题是 jQuery.ajax() 从工厂返回的对象调用 showErrorStatus() 函数——我的代码中没有调用此函数的地方。
我喜欢从使用这个对象中获得的 OOP 品质,那么有没有什么方法可以在不进行重大重写的情况下处理这种情况(例如,从“类”中删除我的所有功能)?
注意:我发现很难解释这个问题,所以这里是一个完整的运行 example on jsfiddle .
最佳答案
使用 JSON.stringify
(不是 jQuery 方法)。
$.ajax({
url: '/echo/json/',
type: 'GET',
data: JSON.stringify(myObject),
dataType: 'json',
});
关于javascript - 为什么 jQuery.ajax() 调用我的对象函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15014396/