简体   繁体   English

使用jQuery直接将变量传递给$ .post()函数

[英]Pass variable directly to $.post() function with jQuery

I'm using the following $.post syntax to retrieve json data from a database and I pass that to a function that appends them to a certain(!) div. 我正在使用以下$.post语法从数据库中检索json数据,并将其传递给将它们附加到确定(!)div的函数。

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

Can I, from this line here above, pass a variable directly to my function? 我可以从上面的这一行直接将变量传递给我的函数吗? Due to some glitch, I've created a bug in my script. 由于某些故障,我在脚本中创建了一个错误。

I have a lot of divs with the class 'x', and when a user selects one, its class is set to 'selected'. 我有很多具有类“ x”的div,并且当用户选择一个时,其类将设置为“选定”。 The function in the above post request only targets that: $('div#selected') , however, if by the time the response comes through the user selects another div, the data from the server gets appended to the wrong div. 上面发布请求中的函数仅针对以下目标: $('div#selected') ,但是,如果在响应通过用户选择另一个div时,来自服务器的数据将附加到错误的div上。

I'd like to pass the id of the selected div to my function, so that there could be no confusion in what goes where. 我想将选定的div的id传递给我的函数,这样就可以避免混淆。 Is there a way to do that? 有没有办法做到这一点?

Right now, Im thinking of passing the id to the request.php and return it back as part of the json, but that would so not be elegant. 现在,我正在考虑将id传递给request.php并将其作为json的一部分返回,但这并不是很优雅。

I'd like to pass the id of the selected div to my function, so that there could be no confusion in what goes where. 我想将选定的div的id传递给我的函数,这样就可以避免混淆。 Is there a way to do that? 有没有办法做到这一点?

Yes, You can use $.Proxy to pass in the context of the clicked div. 是的,您可以使用$ .Proxy来传递单击的div的上下文。 And access the id of the id using this.id inside the function. 并在函数内部使用this.id访问ID的ID。

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

Inside your function 内部功能

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
....
}

If you wrap the function call to an anonymous function you can pass whatever parameters you need. 如果将函数调用包装为匿名函数,则可以传递所需的任何参数。

$.post( 
    "request.php", 
    { var1:'var1', var2:var2, .. }, 
    function( data, textStatus, jqXHR ) {
        myownfunction( data, textStatus, jqXHR, myVariable );
    },
    "json" 
);

If you use $.ajax instead of $.post you can use its context setting to explicitly set the callback's this value as required: 如果使用$.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
    ...
}         

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

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