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)

    评论

报告相同问题?