0

我使用以下$.post语法从数据库中检索 json 数据,并将其传递给将它们附加到某个(!)div 的函数。

$.post("request.php", { var1:'var1', var2:var2, .. }, myownfunction, "json" );

我可以从上面的这一行直接将变量传递给我的函数吗?由于一些故障,我在脚本中创建了一个错误。

我有很多带有“x”类的 div,当用户选择一个时,它的类被设置为“已选择”。上述 post 请求中的函数仅针对:$('div#selected')但是,如果在通过用户选择另一个 div 的响应时,来自服务器的数据将附加到错误的 div 中。

我想将所选 div 的 id 传递给我的函数,这样就不会混淆去哪里了。有没有办法做到这一点?

现在,我正在考虑将 id 传递给 request.php 并将其作为 json 的一部分返回,但这并不优雅。

4

3 回答 3

2

我想将所选 div 的 id 传递给我的函数,这样就不会混淆去哪里了。有没有办法做到这一点?

是的,您可以使用$.Proxy来传递单击的 div 的上下文。this.id并使用函数内部访问 id 的 id 。

$.post("request.php", 
                { var1:'var1', var2:var2, .. }, 
                $.proxy(myownfunction, elem), "json" );

在你的函数里面

function myownfunction( response )
{
....
    this.id // here will be the id of the element passed if it is the clicked div then you will get it here
....
}
于 2013-05-05T07:28:58.030 回答
1

如果你使用$.ajax而不是$.post你可以使用它的context设置来根据需要显式设置回调的this值:

$.ajax('request.php', {
    type: 'POST',
    data: { ... },
    context: mydiv
}).done(myownfunction);

function myownfunction(data) {
    var id = this.id;     // extracting the element here
    ...
}         
于 2013-05-05T07:47:32.833 回答
1

如果将函数调用包装到匿名函数,则可以传递所需的任何参数。

$.post( 
    "request.php", 
    { var1:'var1', var2:var2, .. }, 
    function( data, textStatus, jqXHR ) {
        myownfunction( data, textStatus, jqXHR, myVariable );
    },
    "json" 
);
于 2013-05-05T07:26:32.867 回答