donglu9743 2014-12-09 01:25
浏览 48
已采纳

从php文件返回json到ajax [关闭]

Seems to be everything ok, but I can't access the data inside the javascript. I know its something easy and have a lot of tutos everywhere, but I'm a little confused. Someone can help me?

Here is the three pieces of code, really simple:

foo.js


$.ajax({ 

    data: {'termo': termo},
    url: 'http://localhost/tarefa66/sysvendas/getFestas.php',
    success: function(data) {
    $('#resultado').text(JSON.parse(data)[0]);
    }


});

getFestas.php


    echo json_encode(getFestas($_GET['termo']));

dao.php


    $getFestas = $pdo->query("SELECT * FROM festa f WHERE f.nome LIKE '%" . $termo . "%'");

    return $getFestas->fetchAll(PDO::FETCH_OBJ);

Output on network tab (Firefox) http://i.stack.imgur.com/JfKuS.png

============================================================

Problem solved. 1. The complete method don't receive 'data', 'success' do.

The php return is something like '[{"prop": 'value'}]', so doing this 'JSON.parse(data)[0]' I was just accessing the Object inside the array - that can't be printed.

So the right use is: obj = JSON.parse(data)[0]; and after access like obj['prop'].

  • 写回答

2条回答 默认 最新

  • dongtang5776 2014-12-09 02:06
    关注

    I think the problem is that you're trying to set text to a javascript object instead of a string. try

        complete: function(data) {
            $('#resultado').text(JSON.stringify(JSON.parse(data)[0]));
        }
    

    If that doesn't work, try setting the data type to json explicitly. Then you can access data as a javascript object without parsing it yourself.

    $.ajax({ 
    
        data: {'termo': termo},
        url: 'http://localhost/tarefa66/sysvendas/getFestas.php',
        dataType: "json",
        complete: function(data) {
            $('#resultado').text(data[0]);
        }
    
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64