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 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)