【问题标题】:display results from users input with API data using jquery使用 jquery 显示用户使用 API 数据输入的结果
【发布时间】:2018-11-14 04:37:29
【问题描述】:

我是 jQuery、API 和 HTML 的新手。我的 HTML 页面的目标是让用户输入年份并从下拉列表中选择月份。然后“列出事件”按钮将根据用户的输入显示表格。但是,该表显示所有结果。任何帮助将不胜感激。谢谢你

JS:

$(document).ready(function() {

//populate dropdown
var val,
    text;
for (text in months) {
    val = months[text];
    $('<option/>').val(val).text(text).appendTo($('#months'));
}
// List incidents Button
$("#getButton").click(function() {
    getData();


});
});
function makeURL(year, month){
let base = "https://moto.data.socrata.com/resource/jfwn-iu5d.json"
}

function getData() {
var year = $('#year').val();
//    var month = $('#months').val();
var url = "https://moto.data.socrata.com/resource/jfwn-iu5d.json";

$.ajax({
    url: url,
    Type: "GET",
    dataType: "json",
    data:{
       month: month,
        year: year,
    },
    success: function(data) {
        console.log("success");
        var data = data.filter(a=> (new 
Date(a.incident_datetime).getMonth()+1) === parseInt(month) && new 
 Date(a.incident_datetime).getFullYear() === parseInt(year));

        for (i = 0; i < data.length; i++) {
            crime = data[i];
            var dateTime = crime["incident_datetime"];
            var dateInfo = new Date(dateTime);
            var date = calendarDate(dateInfo);
            var day = crime["day_of_week"];
            var time = timeStamp(dateInfo);
            var description = crime["incident_description"];
            var description = descriptionSelection(description)
            var tableRow = "<tr><td>" + date + "</td><td>" + day + "</td> 
 <td>" + time + "</td><td>" + description + "</td></tr>";
            $("#output").append(tableRow);
        }
    }
});
}


// Function to only display descriptions of incidents
function descriptionSelection(description) {
description = description.split("P:")[0];
return description;
}

// Function to display time
function timeStamp(dateInfo) {
var time = dateInfo.toLocaleTimeString(undefined, {
    hour: "2-digit",
    minute: "2-digit",
});
return time;
}

// Function to display MMM/DD/YYYY
 function calendarDate(dateInfo) {
var date = dateInfo.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric"
});
return date;
}

var days={
'Select Month': '',
'Monday' : 'Monday',
'Tuesday' : 'Tuesday'
}   ;
// map containing months
var months = {
'Select Month': '',
'January': 'JAN',
'February': 'FEB',
'March': 'Mar',
'April': 'APR',
'May': 'MAY',
'June': 'JUN',
'July': 'JUL',
'August': 'AUG',
'September': 'SEP',
'October': 'OCT',
'November': 'NOV',
'December': 'DEC'
};

HTML:

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink- 
to-fit=no">
<link rel="stylesheet" 
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" 
integrity="sha384- 
Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
 crossorigin="anonymous">
<link rel="stylesheet" href="css/worcester.css">
<title> Worcester Crime Report</title>
</head>

<body>
<main role="main" class="container-fluid">

    <!--Navigation bar -->
    <nav class="navbar navbar-light ">
        <a class="navbar-brand" href='#'>
            <img src="image/Worcester_logo.png" width="30" height="30" 
class="d-linline-block align-top" alt="">
             City of Worcester</a>

        <!-- Toggler/ collapsible Button-->
        <div>
            <button type="button" id="navButton" class="navbar-toggle" data- 
toggle="collapse" data-target="#collapsibleNavbar">
                <span class="navbar-toggler-icon"> </span>
            </button>
        </div>


        <!--- Navigation bar links --->
        <div class="collapse navbar-collapse" id="collapsibleNavbar">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="#">Crime Data</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="crimeStats.html">Crime 
 Stats</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" target="_blank" 
href='https://www.crimereports.com/agency/worcesterma#!/dashboard?'
                        Police Department </a>
                </li>
            </ul>
        </div>
    </nav>
    <br>
    <h2> Crime Record in Worcester, MA </h2>
    <br>
    <p>This app provides a list of crimes with dates and times of the 
occurrances in Worcester, Massachusetts.</p>

    <!---Search year and months --->
    <div class="row">
        <div class="col">
            <input type="number"class="form-control" placeholder="Year YYYY" 
id="year" min="2011">
        </div>
        <div class="col">
            <select name="months" class="form-control" id="months">
            </select>
        </div>

        <div class="col">
            <button type="button" id="getButton" class="btn btn-info">List 
 Incidents</button>
        </div>
    </div>
    <div class="error"></div>

    <br>
    <div class="overflow-x:auto">
        <table class=" table table-hover" id="output">
            <thead class="thead-dark">
                <th>Date</th>
                <th>Day</th>
                <th>Time</th>
                <th>Description</th>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>

    <br>

</main>

<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256- 
FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"> 
</script>

<script src="scripts/w2.js"></script>
</body>

</html>

【问题讨论】:

  • 也添加您的 HTML
  • 我们没有你所有的 JavaScript 代码,我们需要你的 HTML 代码。
  • 我刚刚发布了 HTML

标签: jquery html json api


【解决方案1】:

这里有很多问题,

  1. 月份绑定不正确
  2. 您没有在结果中应用任何过滤器
  3. 您需要根据自己的要求调整此更改。

我已经添加了 cmets 的变化你可以看一下演示

$(document).ready(function() {

//populate dropdown
var val,
    text;
    var index =1;
for (text in months) {

    val = months[text];
    $('<option/>').val(index).text(text).appendTo($('#months'));
    index++;
}
// List incidents Button
$("#getButton").click(function() {
    getData();


});
});
function makeURL(year, month){
let base = "https://moto.data.socrata.com/resource/jfwn-iu5d.json"
}

function getData() {
var year = $('#year').val();
var month = $('#months').val();
var url = "https://moto.data.socrata.com/resource/jfwn-iu5d.json";

$.ajax({
    url: url,
    Type: "GET",
    dataType: "json",    
    success: function(data) {
        console.log("success");
        var data = data.filter(a=> (new 
Date(a.incident_datetime).getMonth()+1) === parseInt(month) && new 
 Date(a.incident_datetime).getFullYear() === parseInt(year));

        for (i = 0; i < data.length; i++) {
            crime = data[i];
            var dateTime = crime["incident_datetime"];
            var dateInfo = new Date(dateTime);
            var date = calendarDate(dateInfo);
            var day = crime["day_of_week"];
            var time = timeStamp(dateInfo);
            var description = crime["incident_description"];
            var description = descriptionSelection(description)
            var tableRow = "<tr><td>" + date + "</td><td>" + day + "</td><td>" + time + "</td><td>" + description + "</td></tr>";
            $("#output").append(tableRow);
        }
    }
});
}


// Function to only display descriptions of incidents
function descriptionSelection(description) {
description = description.split("P:")[0];
return description;
}

// Function to display time
function timeStamp(dateInfo) {
var time = dateInfo.toLocaleTimeString(undefined, {
    hour: "2-digit",
    minute: "2-digit",
});
return time;
}

// Function to display MMM/DD/YYYY
 function calendarDate(dateInfo) {
var date = dateInfo.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric"
});
return date;
}

var days={
'Select Month': '',
'Monday' : 'Monday',
'Tuesday' : 'Tuesday'
}   ;
// map containing months
var months = {
'Select Month': '',
'January': 'JAN',
'February': 'FEB',
'March': 'Mar',
'April': 'APR',
'May': 'MAY',
'June': 'JUN',
'July': 'JUL',
'August': 'AUG',
'September': 'SEP',
'October': 'OCT',
'November': 'NOV',
'December': 'DEC'
};
Try month:01 year:2017
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main role="main" class="container-fluid">   

    <!---Search year and months --->
    <div class="row">
        <div class="col">
        Year:
            <input type="number"class="form-control" placeholder="Year YYYY" 
id="year" min="2011">
        </div>
        <div class="col">
        Month:
            <select name="months" class="form-control" id="months">
            </select>
        </div>

        <div class="col">
            <button type="button" id="getButton" class="btn btn-info">List 
 Incidents</button>
        </div>
    </div>
    <div class="error"></div>

    <br>
    <div class="overflow-x:auto">
        <table class=" table table-hover" id="output">
            <thead class="thead-dark">
                <th>Date</th>
                <th>Day</th>
                <th>Time</th>
                <th>Description</th>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>

    <br>

</main>

【讨论】:

  • 嗨。以下是我的完整 js 代码,我也添加了您的建议。我认为之前不需要它。结果未显示。
  • 对不起。我刚刚用完整的代码编辑了我的帖子。这是我第一次使用 stackOverflow。请和我一起裸露。谢谢你的帮助。我添加了你的建议,表格没有显示任何数据。
  • @Madeline 我已经更新了我的答案,请仔细看看,现在很容易实现。
  • 我能够记录两次“成功”,但仍然没有显示数据表
  • 哪个月哪个年?在控制台中检查收到的结果并据此应用过滤器,ti 应该可以工作
【解决方案2】:

您似乎没有将 yearmonth 变量传递到 URL。由于您使用的是 GET 方法,因此有两种方法可以执行此操作。由于我不熟悉有问题的 URL,我只是在猜测/假设端点和参数。

选项 1,附加到 URL。

var url = "https://moto.data.socrata.com/resource/jfwn-iu5d.json?month=" + month + "&year="+year;

选项2,将其添加到带有数据函数的ajax调用中。

...
type: "GET",
data: {
    Month: month,
    Year: year,
},
...

假设

  • 您想要传递 monthyear 变量。
  • 他们接受参数MonthYear

【讨论】:

  • 如果您只是复制并粘贴该代码,它可能无法正常工作 - 就像提到的那样,我不知道 URL 参数,因此您必须将 Month 和 Year 键替换为他们接受什么。即:TheMonth: month, TheYear: year.
  • 谢谢。我现在明白你的意思了。当参数与数组完全相同时,它可以工作。但是,“年”在由日期和时间组成的“incident_dateTime”(“2017-01-21T00:40:35.000”)中。无论如何我只能将“incident_dateTime”中的年份作为参数?
  • 看看 Just Code 的解决方案。如果他们不允许在 URL 中使用参数进行过滤,那么您将不得不在您的最后进行过滤。查看success 函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2022-11-16
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
  • 2013-07-22
  • 1970-01-01
相关资源
最近更新 更多