输出PHP已经编码为json,并发送到javascript为json,不起作用

问题描述 投票:0回答:4

我使用

json_encode
进行输出以发送到 javascript,使用此代码。

<?php

    include "Connection.php";

    $syntax_query = "select * from product";

    $thisExecuter = mysqli_query($conn, $syntax_query);

    $result = array();

    while($row = mysqli_fetch_assoc($thisExecuter)){
        
        array_push(
            $result,
            array(
                "id"       => $row["product_id"],
                "name"        => $row["product_name"]
            )
        );
    }

    echo json_encode($result);

    ?>

所以输出显示如下:

[
    { "id": "121353568", "name": "Baju Casual - Black" }, 
    { "id": "556903232", "name": "Tas LV - Red" },
    { "id": "795953280", "name": "Sword - Wood" },
    { "id": "834032960", "name": "Scooter - Iron Plate" }
]

Javascript 代码如下:

function showHint() {
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
        var obj = this.responseText;
        
        document.getElementById("txtHint").innerHTML = obj.id;
    }
  xmlhttp.open("GET", "Download.php");
  xmlhttp.send();
}

obj.id
不起作用,输出显示“未定义”。

javascript php html json xmlhttprequest
4个回答
0
投票

当我想调用 Php 文件并从与下面相同的内容获取响应时,我使用 ajax 调用,如我所示,尝试一次。在使用 Ajax 之前,您必须需要将 jquery 导入到调用文件中。


如果导入了Jquery则忽略这些步骤


以下是步骤,

  1. 转到链接https://code.jquery.com/jquery-3.6.0.min.js复制全部内容(使用ctl+A选择全部内容,然后使用ctl+C复制)
  2. 在当前项目文件夹中打开一个新文件,粘贴复制的内容(使用ctl+V粘贴)保存为'jquery-3.6.0.min.js'
  3. 在script标签中导入HTML文件中的js文件,如图'

现在,这是调用 PHP 文件并获取响应的 ajax 示例

function showHint() {
//since you have used GET method I have used here GET but You can use POST also here 
 $.ajax({
    url: 'Download.php',
    type: 'get',
//if any value you want to pass then uncomment below line
//    data: {'name_to_pass':'value'}, 
//the variable can be accessed in the php file by 'name to pass' under $_GET['name_to_pass'] or $_POST['name_to_pass'] based on type
    success: function(res)
    {
      //  open DevTool console to see results
      console.log(JSON.parse(res));
    }
    });
}
希望这对你有帮助,谢谢


0
投票

也许您需要在响应中使用 JSON.parse,例如

JSON.parse(this.responseText)

我还可以看到结果是一个数组,所以你需要迭代

obj

obj.forEach(item => { 
  document.getElement("txtHint").innerHTML = item.id;
});
        

0
投票

您应该将响应类型定义为 json

header('Content-Type: application/json; charset=utf-8');

echo json_encode($result);

0
投票
function showHint() {
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
        **var obj = this.responseText;**
        
        document.getElementById("txtHint").innerHTML = obj.id;
    }
  xmlhttp.open("GET", "Download.php");
  xmlhttp.send();
}

当您获得responseText时,它是文本,而不是对象。

var obj = this.responseText;
应该是
let obj = JSON.parse(this.responseText);
然后你就可以将 obj.id 作为属性来访问。

© www.soinside.com 2019 - 2024. All rights reserved.