douzhai1182 2017-06-18 01:37
浏览 45
已采纳

从JavaScript调用PHP JSON数据

I am attempting to obtain PHP data from my Javascript code. This is meant to be shown in the dayta div id. What I end up getting instead is undefined instead of the desired result (which in this instance is the firstname in my JSON file). I am not sure why this is happening.

My JavaScript code:

window.onload = function(){
    var http = new XMLHttpRequest();
    http.onreadystatechange = function(){
        if (http.readyState == 4 && http.status == 200){
            var dayta = document.getElementById('datadisplay');
                dayta.innerHTML = http.response.firstname;
        }
    }
    http.open("GET", "myphpfile.php", true);
    http.send();
}

My PHP code (myphpfile.php):

<?php   
    $content = file_get_contents('somejsonfile.json');
    print_r($content);
    $dbcon->close();
?>

The PHP code included is only a portion of my code, but it contains all the parts relevant to my problem.

$content outputs a JSON file, as that is what it is pointed to. If I echo $content I am able to verify that the content is streamed out as intended.

Thus, the problem is most likely with my JavaScript code. But I cannot identify specifically what is wrong.

My JSON file (somejsonfile.json):

{"firstname": "Ki ki ki ma ma ma"}

I understand that the most obvious way to approach this specific example is to simply have the JavaScript file reach the JSON file. However, since I'm trying to secure the path of my JSON file in my production code I am trying out this method.

  • 写回答

2条回答 默认 最新

  • douqingzhi0980 2017-06-18 01:44
    关注

    Make sure you get a JSON response by using JSON.parse. Here's a quick solution. I have tried it and it works great!

    window.onload = function(){
        var http = new XMLHttpRequest();
        http.onreadystatechange = function(){
            if (http.readyState == 4 && http.status == 200){
                var dayta = document.getElementById('datadisplay');
                var data = JSON.parse(http.responseText);
                dayta.innerHTML = data.firstname;
            }
        }
        http.open("GET", "myphpfile.php", true);
        http.send();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 arcgis中更新地理配准后几个图层分离怎么解决?
  • ¥15 想请教大家关于机器学习的问题
  • ¥15 虚幻UE保存Actor位置失败
  • ¥15 多个.nii合并为.nii.gz格式
  • ¥50 现在需要统计2023年全年 “签收时间(qssj)” 到 “提交时间(tjsj)” 小于半小时的业务量,但是要排除掉周末的时间,同时还要排除中午休息的时间。
  • ¥50 opencv模板匹配为何图像差别大仍然匹配数值高?
  • ¥15 如何成功完成主菜单和分菜单的代码编程C++
  • ¥15 怎样采集或者其它途径拿到全国最新个体工商户数据
  • ¥20 我是一名大学生,想学习java是自学还是报培训班呢
  • ¥15 pycharm该如何爬取网易云歌曲下的评论?