【问题标题】:Ajax call function with parameter / unlike and like Article带参数的ajax调用函数/like和like文章
【发布时间】:2020-10-29 05:42:41
【问题描述】:

我想喜欢或不喜欢一篇文章。我有一个实体 ArticleLike。 要注册“喜欢”,我在我的 ajax 中调用此函数:

url : '{{ path('post_like', {'id' : article.id, 'like' : 1}) }}'

但是当我喜欢时属性'like'是1,而当我不喜欢时属性'like'是0

我希望有 2 个按钮来调用这个 ajax 函数,并根据按钮调用向 ajax 函数发送 0 或 1

$(document).on('click', '#ajax', function(){  
  that = $(this);
  $.ajax({
       url : '{{ path('post_like', {'id' : article.id, 'like' : 1}) }}',
       type : 'POST',
       dataType : 'html',
       success : function(code_html, statut){ 
         code = JSON.parse(code_html);
         $("a.likeChange").html(code.likes);
         console.log(code_html)
     },
       error : function(resultat, statut, erreur){
       }
    });
    return false;
});

【问题讨论】:

    标签: ajax symfony


    【解决方案1】:

    通常,在 javascript 中插入 twig 变量或函数是不好的做法。您可以做的是向按钮添加数据属性:

    <button data-url="{{ path('post_like', {'id' : article.id, 'like' : 1}) }}">Like</button>
    

    另一个是 0。然后在你的ajax中你可以得到url:

    let url = $(this).data('url');
    

    【讨论】:

    • 当我这样做时,我在控制台中发现未定义:let url = $(this).data('url'); console.log(url)。和按钮&lt;a id="ajax" data-url="{{ path('post_like', {'id' : article.id, 'like' : 1}) }}" class="btn" role="button"&gt;&lt;/a&gt;
    • 你能复制它吗?工作正常here
    • 对不起,我做错了..我调用了错误的函数。所以你做的很好 ty
    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    相关资源
    最近更新 更多