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

从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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵