douxigai8757
douxigai8757
2015-08-20 19:00

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 duanliao3826 6年前

    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);
    
    点赞 评论 复制链接分享