首页 > 解决方案 > 从 JSON API 获取数据(从一台服务器)并在 HTML 上显示(到另一台服务器)

问题描述

我有两个不同的项目,不知何故我必须将数据从 Project1 传递到 Project2。所以我决定将数据库中的 Project1 数据作为 JSON API 并使用 Project2 的 HTML 页面来调用它。但是数据没有成功显示。

JSON 文件如下所示:

{
    "data": [
        {
            "title": "Corporate Finance",
            "responsibilities": "Responsible for financial accounting and reporting, internal controls, budgetary control, variance analysis.",
            "requirements": "Candidate must possess at least a Degree in Accountancy or Professional Degree or equivalent.",
            "status": "1"
        },
        {
            "title": "Group Reporting Accountant",
            "responsibilities": "We are seeking a Group accountant to take full financial responsibility for the Group Consolidation and Reporting. Reporting to the Regional Financial Controller, you will be responsible for formulati",
            "requirements": "Prepare monthly financial statements for the business and to consolidate the group accounts.",
            "status": "1"
        }
    ]
}

我尝试在 Project2 HTML 页面下使用 AJAX 来提出请求:

$.ajax({
        url: 'http://localhost/dbpass/api/post/read.php',
        dataType: "text",
        success: function(data) {
            // Parse JSON file
            var json = $.parseJSON(data);
            //Store data into a variable
            // Display 
            $('#results').html(json.data);
        }
      });

并在 HTML 上显示:

<span id="results"></span>

我对此很陌生,如果这是一些愚蠢的错误,请原谅我,谢谢!

标签: javascriptjqueryhtmljson

解决方案


打印可以使用JSON.stringify的对象内容。

$('#results').html(JSON.stringify(json.data, null, 4));


推荐阅读