weixin_33725126 2014-01-10 16:59 采纳率: 0%
浏览 78

jQuery AJAX->获取ID

I have the following code:

<script type="text/javascript">
$(document).ready(function(){
    $('#writeReview').click(function(){
        var id =  $('.ajaxsend').attr('id');
        var link = 'writereview/' + id;
        console.log(id);
        console.log('In the click');
    })

    $('.login_form').on('submit', function(e) {
        $.post( 'writereview/' , $(this).serialize(), function(response) {
            $("#login_message").html( response );
        });
        // disable default action
        e.preventDefault();
    });
});
</script>

How can I get the var link in the HREF for the post? The link starts always with writereview/ and then an ID. Anyone that can help me?

  • 写回答

2条回答 默认 最新

  • weixin_33691817 2014-01-10 17:02
    关注

    You need to define the variables in the right scope (so outside any functions) like this:

    var id;
    var link;
    
    $(document).ready(function () {
        $('#writeReview').click(function () {
            id = $('.ajaxsend').attr('id');
            link = 'writereview/' + id;
            console.log(id);
            console.log('In the click');
        })
    
        $('.login_form').on('submit', function (e) {
            if (!link) 
                return;
    
            $.post(link, $(this).serialize(), function (response) {
                $("#login_message").html(response);
    
            });
            // disable default action
            e.preventDefault();
        });
    });
    

    So if you click the #writeReview button first and then do the submit it should work.

    As long as the variables are defined in the right scope it is fine (so you could place them, as A. Wolff mentioned inside the document ready)

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题