繁体   English   中英

为什么会出现“ Uncaught ReferenceError:未定义userId”错误?

[英]Why am I getting “Uncaught ReferenceError: userId is not defined” error?

即使我的alert($ userId)打印出1(这是用户的ID),我仍然会收到错误,好像没有定义userId一样。 知道为什么吗?

$('.postComment').on('click', function(event){
            event.preventDefault();
            $userId = $("input[name=user_id]").val();
            $imageId = $("input[name=image_id]").val();
            $comment = $("textarea[name=comment]").val();
            alert($userId);

            $.ajax({
                method: 'POST',
                url: urlComment,
                data: {userId: userId, imageId: imageId, comment: comment}
            }).done(function(){
                alert('Works');
            })
        });

您正在使用jQuery,而$在这里有非常不同的用法:

这是您可以尝试的最干净的方法:

    $('.postComment').on('click', function(event){
        event.preventDefault();
        $.ajax({
            method: 'POST',
            url: urlComment,
            data: {
                    userId: $("input[name=user_id]").val(), 
                    imageId: $("input[name=image_id]").val(), 
                    comment: $("textarea[name=comment]").val()}
        }).done(function(){
            alert('Works');
        })
    });

在您的代码中,您有一个名为$ userId的变量,并且您使用的是userId ,但没有声明这就是为什么会出错。

尝试以下

$('.postComment').on('click', function(event){
        event.preventDefault();
        var userId = $("input[name=user_id]").val();
        var imageId = $("input[name=image_id]").val();
        var comment = $("textarea[name=comment]").val();
        alert(userId);

        $.ajax({
            method: 'POST',
            url: urlComment,
            data: {userId: userId, imageId: imageId, comment: comment}
        }).done(function(){
            alert('Works');
        })
    });

要么

$('.postComment').on('click', function(event){
        event.preventDefault();
     var   $userId = $("input[name=user_id]").val();
     var   $imageId = $("input[name=image_id]").val();
     var $comment = $("textarea[name=comment]").val();
        alert($userId);

        $.ajax({
            method: 'POST',
            url: urlComment,
            data: {userId: $userId, imageId: $imageId, comment: $comment}
        }).done(function(){
            alert('Works');
        })
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM