开发者

$.get sends prototype functions in request URL?

I have some prototype functions added to Object which in my opinion were practical in certain scenarios. However, I noticed that when I executed a $.get, the prototype functions are handled as data members and are sent like http://...?prototypefunc=false.

This is rather useless as I don't supply these as data开发者_StackOverflow社区 members, but they are added to the query string.

To be exact, I have this code:

Object.prototype.in = function() {
    for(var i=0; i<arguments.length; i++)
       if(arguments[i] == this) return true;
    return false;
}

$.get('http://localhost/test.php', {'test': 'foo'}, function(text) { });

The corresponding URL constructed is:

http://localhost/test.php?test=foo&in=false

How can I avoid this?


jQuery runs a for...in loop on the object passed, which iterates over all enumerable properties of an object, whether inherited or not. It doesn't do any checks to see if the object's property is owned by the object or inherited via the prototype chain.

Also, if it encounters a property whose value is a function during the serialization of the object it will execute the function and use the return value.

There are a few solutions:

  • Change your code so that it doesn't modify Object.prototype.
  • Pass a string instead of an object, or serialize the object to a string using your own code.
  • Override the jQuery.param() function with your own, and force it to check each property with .hasOwnProperty(propertyName).
  • Make the property on the prototype chain non-enumerable by using Object.defineProperty() (ECMAScript 5 compliant browsers only).


In your case, if you dont't want to remove that in function, you should serialize data (with function, which works similary to jQuery serialize) to string and append it to URL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜