Post 方法使用 jquery 的对象

Post object with methods using jquery

我有一个简单的对象

function MyClass()
{
    this.id = null;
    // ... Lot of stuff in it
}
MyClass.prototype.parse = function(text)
{
    // A parsing function that fills the object
}

如果我尝试使用 $.post

发送对象
$.post("target.php", { QUERY: "query_id", object: obj }, function(data){
    console.log(data);
}, 'json');

objMyClass 的一个实例,我得到一个错误:text is undefined

我如何让它明白我只想要发送数据,而不是像 parse 这样的方法,因为它没有任何意义?

调用Ajax时,只能发送字符串。它会自动将数据转换为字符串,但如果不能,就像您的情况一样,它会抛出错误。在这种情况下,不是发送 obj,而是发送 obj.data(字符串值)。

您可以通过执行以下操作来迭代对象的属性

for (var prop in obj)

将它与 typeof 结合使用以确定 属性 是否是一个函数,您可以创建一个函数来 return 所有非函数属性作为一个新对象。我以这个 jsfiddle 为例。

http://jsfiddle.net/6w0wj8hj/

这意味着您可以这样做

$.post("target.php", { QUERY: "query_id", object: obj.getProperties() }, function(data){
    console.log(data);
}, 'json');