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

标签 javascript jquery

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

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

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

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

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

现在,我正在考虑将 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. Is there a way to do that?

是的,您可以使用$.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
....
}

关于javascript - 使用 jQuery 将变量直接传递给 $.post() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16382303/

相关文章:

javascript - Backbone JS 和 JQuery 插件架构在 Mini Photoshop 项目中一起使用

javascript - 为什么我的 Sass 在使用 Gulp 时没有出现?

javascript - react.js 的 Paypal 按钮

javascript - snackbar 验证 MDL - Javascript/Jquery

javascript - 使用相应的记录内容更新 jquery 对话框表单

javascript - 我将如何编写一个变量来使用 Jquery 调用页面上所有元素的所有边距?

javascript - 依靠javascript进行菜单布局可以吗?

javascript - 谷歌浏览器扩展。本地获取json数据

javascript - 在辅助屏幕上定位弹出窗口

javascript - 为什么这只能在页面加载时正常工作?