将数据从Ajax传递到PHP,导致语法错误

时间:2016-03-31 03:04:27

标签: javascript php jquery html ajax

我在使用Ajax和PHP时遇到错误。

在浏览器控制台中我收到此消息:发生以下错误:parsererror SyntaxError:意外的令牌<。我似乎无法弄清楚它的来源,并尽可能多地尝试调试它。

在main.js中:

$(document).ready(function(){
    $(".post").click(function(){
        var number = {event_number: this.id}; //This gets the ID of the element clicked
        $.ajaxSetup ({
            cache:false
        });
        request = $.ajax ({
            type: "GET",
            url: "event_page.php",
            data: number,
            dataType: 'json'
        });

        request.done(function(response){
            var resultsArray = response;
            console.log(resultsArray);
            $("#main").text(resultsArray);
        });

        request.fail(function (jqXHR, textStatus, errorThrown){
            console.error("The following error occured: " + textStatus,     errorThrown);
        });
    });
});

在event_page.php中:

<?php
    $data = json_decode(stripslashes($_GET['data']), true);
    $event_number = $data['event_number'];
    echo $event_number;
?>

修改

以下是控制台中显示的完整错误消息:

The following error occured: parsererror SyntaxError: Unexpected token <
at Object.parse (native)
at n.parseJSON (http://localhost/js/jquery.min.js:4:16756)
at Xb (http://localhost/js/jquery.min.js:4:19069)
at y (http://localhost/js/jquery.min.js:4:22515)
at XMLHttpRequest.c (http://localhost/js/jquery.min.js:4:26989)

我还想指出main.js和event_page.php存在于同一目录中。

正如你在这里看到的,我所要做的就是将元素的ID发送到PHP文件,我正在回应它以验证它是否已被发送。但是,我收到了上面的错误,我不太清楚为什么会发生这种情况。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您正在使用ajax

向服务器发送event_number

你可以这样得到它

$_GET['event_number'];

要以JSON的方式获取发送回复,请尝试以下操作:

<?php
  header('Content-Type: application/json');
  echo json_encode($_GET['event_number']);