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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效