如何将jquery ajax数据提取为html

How to extract jquery ajax data to html?

本文关键字:提取 html 数据 ajax jquery      更新时间:2024-07-02

我很难理解为什么它不起作用。我的.json文件是正确的,但我无法提取数据以在Html上显示它们。

weather.js:

$(document).ready(function() {
    $.ajax({
        url: "weather.json",
        type: "GET",
        dataType: "json", // Returns JSON
        success: function(response) {
            var sTxt = '';
            $.each(response.weather, function(index) {
                sTxt += '<tr><td>' + response.weather[index].name + '</td></tr>';
            });
            $('#weatherlist').append(sTxt);
        },
        error: function() {
            $('#info').html('<p>An error has occurred</p>');
        }
    });
});

weather.html:

<!DOCTYPE html>
<html>
<head>
    <title>Ajax and json Data</title>
    <meta charset="UTF-8">
    <script src="weather.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <header>
        <h1>British and Irish Counties - Weather Data</h1>
    </header>
    <section>
        <table id="weatherlist">
        </table>
        <div id="updatemessage"></div>
    </section>
    <footer>
    </footer>
</body>
</html>

这是新的Html,与之前的现有Html相比,我仍然有一个错误:jquery.min.js:4XMLHttpRequest无法加载file:///C:/Users/jull/Desktop/weather.json.跨源请求仅支持以下协议方案:http、data、chrome、chrome扩展、https、chrome资源扩展。

<!DOCTYPE html>
<html>
<head>
    <title>Ajax and json Data</title>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="weather.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <header>
        <h1>British and Irish Counties - Weather Data</h1>
    </header>
    <section>
        <table id="weatherlist">
        </table>
        <div id="updatemessage"></div>
    </section>
    <footer>
    </footer>
</body>
</html>

打开浏览器的开发工具。查看控制台。它会说:

未捕获的ReferenceError:$未定义

您正在尝试使用jQuery,但尚未包含它。

添加另一个脚本元素(在您已经添加的脚本元素之前),并使用它来加载jQuery库。

You have to use 
JSON.parse(response)