Jquery .ajax 不返回有用的数据


Jquery .ajax doesn't return useful data

我的文件中有一个jquery脚本,上面写着:

<script type="text/javascript">
$(document).ready(function(e){
    $('#myButton').click(function(e){
        var formdata = {name: 'Alan', hobby: 'boxing'};
        var submiturl = 'http://localhost/cake/gronsters/testJSON/';
        $.ajax({
            type: "POST", 
            url: submiturl,
            data: formdata,
            success: function(message){
                console.log(message);
            }
        });
        e.preventDefault();
    })
});

然后我在testJSON上有一个php脚本,上面写着:

public function testJSON(){
    $name = $this->request->data['name'] . '-Sue';
    $hobby = $this->request->data['hobby'] . ' for donuts';
    $data = array(  'name' => $name, 'hobby' => $hobby);
    echo json_encode($data);
}

控制台.log查找消息的地方给了我{"name":"Alan-Sue","hobby":"装箱甜甜圈"},这似乎是正确的,除了它紧随其后的是我网页的完整html。如果我尝试控制台.log(message.name),它会显示"未定义"。

这是怎么回事?

听起来你的/testJSON/页面输出的不仅仅是在你的公共函数中写的内容。 如果您使用的是 MVC 或任何类型的框架,则必须在该回显json_encode后立即退出或死亡,否则页面的其他部分可能仍会呈现。

您走在正确的道路上,尽管正如其他人所提到的,您似乎正在为您的网站使用 MVC 框架,并且在显示 JSON 字符串后包含网页的内容。 如果响应中有其他随机文本或字符,jQuery/JavaScript 无法解析 JSON。在 JSON 回显后,您将需要使用exit;die();,如以下示例所示...

public function testJSON(){
    $name = $this->request->data['name'] . '-Sue';
    $hobby = $this->request->data['hobby'] . ' for donuts';
    $data = array(  'name' => $name, 'hobby' => $hobby);
    // Will halt the script and echo the json-encoded data.
    die(json_encode($data));
}

此外,您需要确保 jQuery 将响应解析为 JSON。默认情况下,它将尝试对返回的数据类型进行智能猜测,但您不能总是依赖它。您应该将dataType选项添加到 AJAX 调用中,如以下示例所示...

<script type="text/javascript">
$(document).ready(function(e){
    $('#myButton').click(function(e){
        // It is best practice to "preventDefault" before any code is executed.
        // It will not cause the ajax call to halt.
        e.preventDefault();
        var formdata = {name: 'Alan', hobby: 'boxing'};
        var submiturl = 'http://localhost/cake/gronsters/testJSON/';
        $.ajax({
            type: "POST", 
            url: submiturl,
            data: formdata,
            // This is the proper data type for JSON strings.
            dataType: 'json',
            success: function(message){
                // JSON is parsed into an object, so you cannot just output
                // "message" as it will just show "[object Object]".
                console.log(message.name);
            }
        });
    });
});
</script>

我在代码中包含了一些注释,以帮助更好地解释。希望这会对您有所帮助。您也不需要使用完整的$.ajax函数,除非您计划使用该函数中的错误处理程序或任何其他更高级的选项。或者,您可以使用 $.post 缩短代码,并使用更少的代码完成与原始示例相同的任务。

<script type="text/javascript">
$(document).ready(function() {
    $('#myButton').click(function(e){
        e.preventDefault();
        var formdata = {name: 'Alan', hobby: 'boxing'};
        var submiturl = 'http://localhost/cake/gronsters/testJSON/';
        $.post(submiturl, formdata, function(message) {
            console.log(message.name);
        });
    });
});
</script>

有关 $.ajax jQuery.ajax() 的更多选项和使用信息;
有关 $.post jQuery.post() 的更多信息;

在尝试记录 message.name 之前,将消息变量解析为 json。

data = $.parseJSON(message);
console.log(data.name);

还要在 php 脚本中 echo 语句之后执行退出并检查。