在调用中使用返回的json值不起作用

using returned json values in calls not working

本文关键字:json 不起作用 返回 调用      更新时间:2024-04-24

试图使用我从php返回的值,但这些值无法正常工作。

<script type="text/javascript">
$(function () {
    $('#delete').on('click', function () {
        var $form = $(this).closest('form');
        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize(),
            dataType : 'json'
        }).done(function (response) {
            if (response.success == 'success') {
                // fade out the deleted comp
                $("#c"+response.computer_id+"").fadeOut("slow");
                // remove from the drop down
                $("#comp_selection option[value='#c"+response.computer_id+"']").remove();
            } else {
                alert('Some error occurred.');
            }
        });
    });
});
</script>

我从php文件返回:

echo json_encode($ajax_result);

正在返回:

{"computer_id":1,"success":"success"}

编辑:我在代码中发现了一个小错误,我返回了一个与预期不同的值。一切都很好,上述内容一开始确实是正确的。

您应该使用firebug或浏览器中的任何开发工具进行调试-firebug在Firefox中非常适用,因为您可以看到AJAX调用返回的JSON数据。

也就是说,你的问题是数据可能正在响应中。d-所以看看response.d.success和response.d.computer_id

也许您从PHP服务器接收的内容是以简单文本的形式发送的,并且必须使用为JSON内容设置的标头发送:

header('Content-Type: application/json');