【问题标题】:Ajax with Express and jquery not working带有 Express 和 jquery 的 Ajax 不起作用
【发布时间】:2014-04-29 18:27:02
【问题描述】:

我的应用中有一个浏览页面,人们可以在其中添加拥有或想要的项目。现在它正在重定向回一般 /browse 页面,但我希望页面根本不刷新。我正在尝试通过 ajax 来做到这一点,但在这方面我是超级新手,无法让它工作。这是我的代码,非常感谢您的帮助:

//HTML file
<div>
    <center><div class="hover">+</div>
    <div class="hovermenu"><a class="addown" pid="<%= p[i].id %>" href="#">&#10004;</a></a></div></center>
</div>


$(".addown").click(function(e){
    $.ajax({
        type: 'POST',
        url: '/addown/' + $(this).('pid'),
        dataType: 'json',
        success: function() {
            $(this).parent().parent().replaceWith('<center><span>&#10004;</span></center>')
        }
    })
    e.preventDefault();
});




//Server side
app.post('/addown/:id', function(req, res) {
    req.user.owned.addToSet(req.params.id);
    req.user.save();
    res.end();
});

非常感谢任何帮助!

【问题讨论】:

  • 我不认为“this”是您在 ajax 调用之后所期望的。
  • 所以我想说$(.addown),但是我如何指定我想要最初点击的那个?
  • 保存,在ajax调用上方添加var ref = this;,然后$(ref).parent...

标签: javascript jquery ajax express


【解决方案1】:

这一行

url: '/addown/' + $(this).('pid'),

有语法错误,我相信你要获取pid属性

url: '/addown/' + $(this).attr('pid')

在你的成功回调中,这不是 div,要将回调的上下文设置为 div,请在你的 ajax 参数中使用 context

url: '/addown/' + $(this).attr('pid'),
context: this,

【讨论】:

  • 你是对的!我解决了这个问题,所以现在控制台实际上将点击显示为正在做某事。但是,div 没有正确替换复选标记。有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-10
  • 2013-02-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
  • 1970-01-01
相关资源
最近更新 更多