douxigai8757 2015-08-20 19:00
浏览 71
已采纳

Php发送JSON响应但$ .getJSON没有收到它

I have a problem with the JSON response I'm returning from my PHP code.

THe PHP on the backend

case 'deleteMySale':
    $id = $_GET['product_id'];
    $dataNoSer = "you want to delete sale where id= " . $id . "?";
    $data =  json_encode($dataNoSer, true);
    echo $data;
    break;

The JavaScript on the front-end that is calling the PHP

$('.deleteProduct').click(function () {
    var id = $(this).data('id');
    $.getJSON("http://localhost/myProject/deleteMySale?product_id=20", function (data) {
        console.log("success");
    })
            .done(function () {
                console.log("second success");
            })
            .fail(function () {
                console.log("error");
            })
            .always(function () {
                console.log("complete");
            });
})

Response

error
complete

The PHP function is called when I click the button, but I consistently get an error in the console.

Why does jQuery not receive the JSON data? I've read similar problems and their solutions, but I canott see where I'm going wrong.

  • 写回答

1条回答 默认 最新

  • duanliao3826 2015-08-20 19:06
    关注

    That's a malformed JSON response. The issue is that you've passed a flat string to the encode function. The encode function does not encode strings, it encodes arrays and objects. Let's make it an array so we can get a real response.

    $dataNoSer = array("question" => "you want to delete sale where id= " . $id . "?");

    Also, if necessary, modify the headers before sending the response so that you're sure it's an application/json content-type on the response.

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

    Access it like so.

    console.log(data.question);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿