简体   繁体   English

为什么jQuery.ajax()调用我的对象函数?

[英]Why is jQuery.ajax() Calling my Objects Functions?

I'm having an issue where jQuery.ajax() is calling my data objects functions. 我遇到一个问题,jQuery.ajax()正在调用我的数据对象函数。 For example, I have an object structure similar to the following: 例如,我有一个类似于以下的对象结构:

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,                
            }
        }
    }
})();

I'd like to use this object as the data value for my jQuery.ajax() call, as follows: 我想使用此对象作为我的jQuery.ajax()调用的数据值,如下所示:

var myObject = TestFactory.createObject(12345);

myObject.attr('name', 'Fred Flinstone');

$.ajax({
    url: '/echo/json/',
    type: 'GET',
    data: myObject,
    dataType: 'json',
});

The issue I'm running into is jQuery.ajax() is calling the showErrorStatus() function from the object returned by the factory --nowhere in my code do I call this function. 我遇到的问题是jQuery.ajax()从工厂返回的对象调用showErrorStatus()函数 - 在我的代码中我是否调用此函数。

I like the OOP qualities I get out of using this object, so is there any way to handle this case without a significant rewrite (eg, dropping all my functionality from the "class")? 我喜欢使用这个对象的OOP特性,所以有没有办法处理这种情况而没有重大的重写(例如,从“类”中删除我的所有功能)?

NOTE: I found it difficult to explain this problem, so here is a complete running example on jsfiddle . 注意:我发现很难解释这个问题,所以这里是一个关于jsfiddle的完整运行示例

It happens because it's a feature, though not documented as far as I can tell. 这是因为它是一个功能,尽管我没有记录。

If you pass an object, then it assumes you want it to call any functions that are values of object properties. 如果传递一个对象,则它假定您希望它调用任何属于对象属性值的函数。

Use JSON.stringify (not a jQuery method). 使用JSON.stringify (不是jQuery方法)。

$.ajax({
    url: '/echo/json/',
    type: 'GET',
    data: JSON.stringify(myObject),
    dataType: 'json',
});

http://jsfiddle.net/HJ9AS/10/ http://jsfiddle.net/HJ9AS/10/

One way of doing it is to use a function like Underscore's pick() . 一种方法是使用像Underscore的pick()这样的函数。 It can be used to cherry-pick certain properties you need from the object. 它可用于从对象中挑选您需要的某些属性。 It is a useful library anyways, but you can also implement this simple method if you wish. 无论如何它都是一个有用的库,但如果你愿意,你也可以实现这个简单的方法。

$.ajax({
    url: '/echo/json/',
    type: 'GET',
    /* only send id and attributes! */
    data: _.pick(myObject, 'id', 'attributes'),
    dataType: 'json',
});

It might be a nice habit to always whitelist stuff , not just send everything blindly. 总是将白名单列入白名单可能是一个好习惯,而不是盲目地发送所有内容。 Specifying exactly what to send can save you from future surprises (like the one you just encountered). 准确指定要发送的内容可以使您免于未来的惊喜(例如您刚刚遇到的那个)。 Most of the time you simply don't want to send everything that is stored in your object. 大多数情况下,您根本不想发送存储在对象中的所有内容。

You can also implement some way for your object to be able to return its sendable contens. 您还可以为对象实现某种方式,以便能够返回其可发送的匹配项。 It could get a .getJSON() method that just collects from the object everything to be sent. 它可以获得一个.getJSON()方法,该方法只从对象中收集要发送的所有内容。


Concerning the function calling: 关于函数调用:

Processing the data property uses $.param() , which has this in the docs: 处理data属性使用$.param() ,在文档中有这个:

As of jQuery 1.3, the return value of a function is used instead of the function as a String. 从jQuery 1.3开始,使用函数的返回值而不是函数作为String。

This is a feature, not a bug :). 这是一个功能,而不是一个bug :)。 I understand the logic behind it, because if there is a function in the object that you just specified as data to be sent, there must be a good reason behind it... 我理解它背后的逻辑,因为如果对象中有一个函数你刚才指定为要发送的数据,那么它背后必然有一个很好的理由......

Instead of passing data: myObject , 而不是传递data: myObject

try setting this: var serializedObject = myObject.param() 尝试设置: var serializedObject = myObject.param()

then passing data: serializedObject 然后传递data: serializedObject

Check out jQuery's param function here . 在这里查看jQuery的param函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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