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条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证