尝试执行 jQuery AJAX 调用时出现 JavaScript 错误意外标识符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7667416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:52:10  来源:igfitidea点击:

JavaScript error unexpected identifier when trying to do jQuery AJAX call

javascriptjqueryajax

提问by Genadinik

I have this jQuery code:

我有这个 jQuery 代码:

<script type="text/javascript">
$(document).ready(function() 
{
    $('.vote_up').click(function() 
    {        
        alert ( "test: " + $(this).attr("data-problem_id") );
        problem_id = $(this).attr("data-problem_id");

        var dataString = 'problem_id='+ problem_id + '&vote=+';

        $.ajax({
                type: "POST",
                url: "/problems/vote.php",
                dataType: "json",
                data: dataString,
                success: function(json)
                {           
                    // ? :)
                    alert (json);


                }
                error : function() 
                {
                    alert("ajax error");
                }
            });


        //Return false to prevent page navigation
        return false;
    });

    $('.vote_down').click(function() 
    {
        alert("down");

        problem_id = $(this).attr("data-problem_id");

        var dataString = 'problem_id='+ problem_id + '&vote=-';        

        //Return false to prevent page navigation
        return false;
    });    
});
</script>

I also have this link HTML:

我也有这个链接 HTML:

        <p class="half_text"><?php echo $upvotes; ?> <strong><a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#" data-problem_id="<?php echo $problem_id; ?>">Vote Up</a></strong> | <?php echo $downvotes; ?> <strong><a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#" data-problem_id="<?php echo $problem_id; ?>">Vote Down</a></strong></p>

When I press the link, I get the Javascript console error "Syntax error: unexpected identifier"

当我按下链接时,出现 Javascript 控制台错误“语法错误:意外标识符”

You can reproduce this by clicking on a vote-up link here http://www.problemio.com

您可以通过单击此处的投票链接来重现此问题http://www.problemio.com

Any idea why this is happening and how to fix it?

知道为什么会发生这种情况以及如何解决吗?

回答by hvgotcodes

no comma between your successand errorcallbacks.

您的successerror回调之间没有逗号。

回答by Seano

In my case I was using the wrong syntax on the server side.

就我而言,我在服务器端使用了错误的语法。

Make sure you use:

确保您使用:

return json_encode($result)

return json_encode($result)

instead of

代替

echo json_encode($result)

echo json_encode($result)