- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试构建一个基本工具来通过邮政编码显示某人的国会代表。
我尝试使用的API通过以下方式免费提供:https://whoismyrepresentative.com
通过邮政编码获取信息的链接是:https://whoismyrepresentative.com/getall_mems.php?zip=31023
也可以将其格式化为json,如下所示:https://whoismyrepresentative.com/getall_mems.php?zip=31023&output=json
我已经阅读了大量有关如何显示此数据的文章,但是我遇到的麻烦是根本无法显示数据。
如何获取数据以显示在页面上。
我的第一次尝试是基于w3schools示例。当单击按钮时,应该在空div中显示结果,但是当我替换URL时,它不显示。当您直接访问URL时,数据就在那里。
我的JavaScript知识非常有限,所以我会逐行介绍,也许我只是误解了一些东西。$(document).ready(function(){
-使文档准备好进行jquery$("button").click(function(){
-在<button>
上设置点击功能$.getJSON("https://whoismyrepresentative.com/getall_mems.php?zip=31023&output=json", function(results){
-我希望这是从API URL获取数据的原因$.each(results, function(i, field){
-我不确定该怎么做,但我认为这会显示“结果”字段$("div").append(field + " ");
-这将在空白的<div>
中显示数据
完整的index.php代码
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Find Your Representative</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("https://whoismyrepresentative.com/getall_mems.php?zip=31023&output=json", function(results){
$.each(results, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Find Your Representative</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// This is your test data
$.getJSON = function(url, callbackFunction) {
var jsonFetchedOn2017_12_21 = {
"results": [{
"name": "Austin Scott",
"party": "Republican",
"state": "GA",
"district": "8",
"phone": "202-225-6531",
"office": "2417 Rayburn HOB; Washington DC 20515-1008",
"link": "https://austinscott.house.gov"
}, {
"name": "John Isakson",
"party": "Republican",
"state": "GA",
"district": "",
"phone": "202-224-3643",
"office": "131 Russell Senate Office Building Washington DC 20510",
"link": "http://www.isakson.senate.gov"
}, {
"name": "David Perdue",
"party": "Republican",
"state": "GA",
"district": "",
"phone": "202-224-3521",
"office": "383 Russell Senate Office Building Washington DC 20510",
"link": "http://www.perdue.senate.gov"
}]
};
callbackFunction(jsonFetchedOn2017_12_21);
}
// I modified this with some alternate names and notes, I also commented out the alerts so I can easily refresh with my constant changes.
// This is the start of the script
function runAfterDocumentLoads() {
causeButtonClicksToLoadJSONData();
}
// This creates the function that when <button> is clicked it will do all the stuff
// I modified this to load on a specific <button> class incase I have multiple buttons.
function causeButtonClicksToLoadJSONData() {
var button = $("button.zip");
button.click(loadJSONData);
}
// So I think this created the variable jQuery represented by a $ I'm not sure I understand why we need it though.
// The json_url stores our URL
// Then we use the jQuery variable to use the jQuery library so we can use getJSON? Could we have used $.getJSON instead?
function loadJSONData() {
var jQuery = $;
var json_url = "https://whoismyrepresentative.com/getall_mems.php?zip=31023&output=json";
jQuery.getJSON(json_url, addJsonToPage);
}
// we set the jQuery variable again here, not sure why we needed it the first time but also why do we need to set it again?
// we set representativeList to be the extractRepresentativeFromJsonResults function
// We use jQuery variable to get the jQuuery library to we can use .each? not sure how this part works but our list and addtopage functions are in it.
function addJsonToPage(jsonResults) {
var jQuery = $;
var representativeList = extractRepresentativeFromJsonResults(jsonResults);
jQuery.each(representativeList, addRepresentativeToPage);
}
// Not sure where jsonObject comes from
function extractRepresentativeFromJsonResults(jsonObject) {
return jsonObject.results;
}
// Not sure where aRepresentative comes from
// I changed the div to have a class since I will definetly have multiple <div>'s going on.
// I modified the whitespace to wrap each name in a div with a class so I can easily style them
// I added phone as well
// The last part is what will add the rep name to div.rep
function addRepresentativeToPage(arrayIndex, aRepresentative) {
var divElementCollection = $("div.rep");
var repName = "<div class=\'name\'>" + aRepresentative.name + "</div>";
var repPhone = "<div class=\'phone\'>" + aRepresentative.phone + "</div>";
divElementCollection.append(repName);
divElementCollection.append(repPhone);
}
// This put the whole thing within .ready so that the script will wait for full page load before it starts.
$(document).ready(runAfterDocumentLoads);
</script>
</head>
<body>
<button class="zip">
Get JSON data
</button>
<div class="rep">
<!-- Output area -->
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Find Your Representative</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// This is your test data
$.getJSON = function(url, callbackFunction) {
var jsonFetchedOn2017_12_21 = {
"results": [{
"name": "Austin Scott",
"party": "Republican",
"state": "GA",
"district": "8",
"phone": "202-225-6531",
"office": "2417 Rayburn HOB; Washington DC 20515-1008",
"link": "https://austinscott.house.gov"
}, {
"name": "John Isakson",
"party": "Republican",
"state": "GA",
"district": "",
"phone": "202-224-3643",
"office": "131 Russell Senate Office Building Washington DC 20510",
"link": "http://www.isakson.senate.gov"
}, {
"name": "David Perdue",
"party": "Republican",
"state": "GA",
"district": "",
"phone": "202-224-3521",
"office": "383 Russell Senate Office Building Washington DC 20510",
"link": "http://www.perdue.senate.gov"
}]
};
callbackFunction(jsonFetchedOn2017_12_21);
}
// After the document is ready it will run the setupPage function which contains the causeButtonClickstoLoadJSONdata function - This setupPage function kind of feels like a wrapper for the rest of the code, does that make sense?
function setupPage() {
causeButtonClicksToLoadJSONData();
}
// We setup a variable called button and set to be <button class="start_request"></button> - Why do we put the jQuery $ in front of this?
// Then we create a .click event on our button variable to run the function clearOutput.
// Then we create another .click event on our button variable to run the function loadJSONData.
// These 2 events will run asynchronously, in order, one after the other, when our button with the class of start_request is clicked.
function causeButtonClicksToLoadJSONData() {
var button = $("button.start_request");
button.click(clearOutput);
button.click(loadJSONData);
}
// We create a variable called outputArea and set it to be a div tag with the class of results.
// Then we use the method .empty on our outputArea variable to remove everything within our <div class="results"></div>.
function clearOutput() {
var outputArea = $("div.results");
outputArea.empty();
}
// We create a variable called json_url and store our API URL in it.
// Then we run the getJSON method to first request the data from our json_url then send the data to our addJsonToPage function?
function loadJSONData() {
var json_url = "https://whoismyrepresentative.com/getall_mems.php?zip=31023&output=json";
$.getJSON(json_url, addJsonToPage);
}
// This is where I have my confusion so bare with me.
// I see there is a jsonResults parameter but I don't know where this came from, is this the data from .getJSON?
// We setup a variable for representativeList and store our extractRepresentativeFromJsonResults function.
// Then we use the .each method which is our loop to run through the array of data. In the .each menthod we use representativeList as the index where all the data is stored and addRepresentativeToPage as the element where we create a function to select the data that we want from extractRepresentativeFromJsonResults.
// I don't fully understand index and element are but that is was I got from reading the jQuery documentation. Index seems to be the list of data, Element seems to be the location where this data will go.
function addJsonToPage(jsonResults) {
var representativeList = extractRepresentativeFromJsonResults(jsonResults);
$.each(representativeList, addRepresentativeToPage);
}
// We need to return this data to use it and we want to return the .results section (there is probably a more correct word to use then section) of the data.
// Why do we start with the parameter as jsonObject and then change to jsoinResults in the addJsonToPage function?
// I believe you were explaining this in the video but it was a little bit hard to hear.
function extractRepresentativeFromJsonResults(jsonObject) {
return jsonObject.results;
}
// I think I am getting lost with parameters I seem to just not know where they come from. arrayIndex makes sense by its name but I don't know why it goes there and what it is doing, same with aRepresentative.
// We set variable for dig tag and results class
// We set variable to get .name, and wrap it in div's
// We set variable to get .phone, wrap it in div's
// We use .append method to add repName to our output div
// We use .append method to add repPhone to our output div
function addRepresentativeToPage(arrayIndex, aRepresentative) {
var divElementCollection = $("div.results");
var repName = "<div class=\'name\'>" + aRepresentative.name + "</div>";
var repPhone = "<div class=\'phone\'>" + aRepresentative.phone + "</div>";
divElementCollection.append(repName);
divElementCollection.append(repPhone);
}
// This will wait for the document to load execute our code
// We do this because if the code is executed before the document is loaded nothing will exist so the code will run on nothing
// Does this need to be the last item on the page? Seemingly we need to wait for the document to load before we can run any code which makes me feel like this should be first.
$(document).ready(setupPage);
</script>
</head>
<body>
<button class="start_request">
Get JSON data
</button>
<div class="results">
<!-- Output area -->
</div>
</body>
</html>
最佳答案
你近了
首先让我解释一下如何解释函数调用。$(document)
是一个jQuery选择器,用于获取活动的HTMLDocument对象。
然后在该对象上调用方法ready
,该方法等待文档完成加载。它是一个事件侦听器,它等待文档的“ onReady”事件。一旦检测到该事件,我们就知道文档及其所有组件已完全加载。
那时,我们在ready
方法调用中执行匿名函数。在那里我们发现:
$("button").click( function(){...} )
$("button")
代码将提取所有加载到具有“按钮”标签名称的文档中的对象。在这种情况下,只有一个按钮。然后调用方法
click
,该方法将事件监听器设置在按钮对象上,并且每次单击关联的按钮时都会调用事件监听器。
$.getJSON("https://whoismyrepresentative.com/getall_mems.php?zip=31023&output=json", function(results){
...
});
$
符号是链接到已加载的jQuery库的变量名。在该库中,我们正在调用
getJSON
方法,该方法将从提供的URL(您的第一个参数)中获取JSON,然后将其异步返回给您提供的任何函数。在这种情况下,您提供了一个匿名函数:
function( results ){
$.each(results, function(i, field){
$("div").append(field + " ");
});
}
$.each()
。
$
是jQuery库。
each()
是一个类似于for ... each循环的函数。
$.each( results, function(i,field){...} );
的调用将执行以下操作。迭代结果对象中的每个项目,然后为每个项目调用一次函数。函数(
i
)中的第一个参数是结果数组中的索引,第二个参数(
field
)是实际项本身。
var exampleData = ["item1","item2","item3"];
$.each( exampleData, function( i, itemName ){ ... } );
function(i, itemName){...}
块的过程中,我将看到以下内容:
i=0
和
itemName="item1"
。
i=1
和
itemName="item2"
。
i=2
和
itemName="item3"
。
$.each( array, function(){} )
会将函数应用于数组的每个元素。
field
变量中,因此在函数执行时:
$("div").append(field+" ");
field
值和空格添加到元素内容的末尾。
console.log(...)
和
debugger
语句来帮助检查代码是否正在运行。当您在控制台中看到每个
field
变量中包含的内容时,您可以更好地了解呈现给您的数据,然后可以更清楚地格式化。
/**
* I am going to override the jQuery.each method for the purpose of this example. This test environment does not allow external calls to
* to fetch other data. This is called a test double... just ignore it.
*/
$.getJSON = function(url, callbackFunction) {
var jsonFetchedOn2017_12_21 = {
"results": [{
"name": "Austin Scott",
"party": "Republican",
"state": "GA",
"district": "8",
"phone": "202-225-6531",
"office": "2417 Rayburn HOB; Washington DC 20515-1008",
"link": "https://austinscott.house.gov"
}, {
"name": "John Isakson",
"party": "Republican",
"state": "GA",
"district": "",
"phone": "202-224-3643",
"office": "131 Russell Senate Office Building Washington DC 20510",
"link": "http://www.isakson.senate.gov"
}, {
"name": "David Perdue",
"party": "Republican",
"state": "GA",
"district": "",
"phone": "202-224-3521",
"office": "383 Russell Senate Office Building Washington DC 20510",
"link": "http://www.perdue.senate.gov"
}]
};
callbackFunction(jsonFetchedOn2017_12_21);
}
/**
* Start paying attention to the code here below....
* This is essentially the same code that you posted in the question, but I have given the anonymous functions names and
* given variables names so that you can understand what each object is.
**/
function runAfterDocumentLoads() {
alert("runAfterDocumentLoads run only after the button and div elements are loaded.");
causeButtonClicksToLoadJSONData();
}
function causeButtonClicksToLoadJSONData() {
alert("After causeButtonClicksToLoadJSONData run, the button click is linked to the function loadJSONData.");
var button = $("button");
button.click(loadJSONData);
}
function loadJSONData() {
alert("loadJSONData runs every time the button is clicked.");
var jQuery = $;
var json_url = "https://whoismyrepresentative.com/getall_mems.php?zip=31023&output=json";
jQuery.getJSON(json_url, addJsonToPage);
}
function addJsonToPage(jsonResults) {
alert("addJsonToPage runs once after jQuery finishes loading each call the requested URL");
var jQuery = $;
//note, I have called the url that you provide and learned that it passes back an array in the results value
var representativeList = extractRepresentativeFromJsonResults(jsonResults);
jQuery.each(representativeList, addRepresentativeToPage);
}
function extractRepresentativeFromJsonResults(jsonObject) {
return jsonObject.results;
}
function addRepresentativeToPage(arrayIndex, aRepresentative) {
alert("addRepresentativeToPage will run once for every item in the representativeList array.");
alert("addRepresentativeToPage adds the item to the div element on the page.");
var divElementCollection = $("div");
var jsonTextWithWhitespace = aRepresentative.name + ", ";
divElementCollection.append(jsonTextWithWhitespace);
}
$(document).ready(runAfterDocumentLoads);
alert("The document has been asked to call runAfterDocumentLoads when it is finished loading.");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Example Button</button>
<div>
<!--Output area-->
</div>
关于javascript - 获取要显示的API数据表单URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47931850/
我有一个 html 格式的表单: 我需要得到 JavaScript在value input 字段执行,但只能通过表单的 submit .原因是页面是一个模板所以我不控制它(不能有
我管理的论坛是托管软件,因此我无法访问源代码,我只能向页面添加 JavaScript 来实现我需要完成的任务。 我正在尝试用超链接替换所有页面上某些文本关键字的第一个实例。我还根据国家/地区代码对这些
我正在使用 JS 打开新页面并将 HTML 代码写入其中,但是当我尝试使用 document.write() 在新页面中编写 JS 时功能不起作用。显然,一旦看到 ,主 JS 就会关闭。用于即将打开的
提问不是为了解决问题,提问是为了更好地理解系统 专家!我知道每当你将 javascript 代码输入 javascript 引擎时,它会立即由 javascript 引擎执行。由于没有看过Engi
我在一个文件夹中有两个 javascript 文件。我想将一个变量的 javascript 文件传递到另一个。我应该使用什么程序? 最佳答案 window.postMessage用于跨文档消息。使
我有一个练习,我需要输入两个输入并检查它们是否都等于一个。 如果是 console.log 正则 console.log false 我试过这样的事情: function isPositive(fir
我正在做一个Web应用程序,计划允许其他网站(客户端)在其页面上嵌入以下javascript: 我的网络应用程序位于 http://example.org 。 我不能假设客户端网站的页面有 JQue
目前我正在使用三个外部 JS 文件。 我喜欢将所有三个 JS 文件合而为一。 尽一切可能。我创建 aio.js 并在 aio.js 中 src="https://code.jquery.com/
我有例如像这样的数组: var myArray = []; var item1 = { start: '08:00', end: '09:30' } var item2 = {
所以我正在制作一个 Chrome 扩展,它使用我制作的一些 TamperMonkey 脚本。我想要一个“主”javascript 文件,您可以在其中包含并执行其他脚本。我很擅长使用以下行将其他 jav
我有 A、B html 和 A、B javascript 文件。 并且,如何将 A JavaScript 中使用的全局变量直接移动到 B JavaScript 中? 示例 JavaScript) va
我需要将以下整个代码放入名为 activate.js 的 JavaScript 中。你能告诉我怎么做吗? var int = new int({ seconds: 30, mark
我已经为我的 .net Web 应用程序创建了母版页 EXAMPLE1.Master。他们的 I 将值存储在 JavaScript 变量中。我想在另一个 JS 文件中检索该变量。 示例1.大师:-
是否有任何库可以用来转换这样的代码: function () { var a = 1; } 像这样的代码: function () { var a = 1; } 在我的浏览器中。因为我在 Gi
我收到语法缺失 ) 错误 $(document).ready(function changeText() { var p = document.getElementById('bidp
我正在制作进度条。它有一个标签。我想调整某个脚本完成的标签。在找到可能的解决方案的一些答案后,我想出了以下脚本。第一个启动并按预期工作。然而,第二个却没有。它出什么问题了?代码如下: HTML:
这里有一个很简单的问题,我简单的头脑无法回答:为什么我在外部库中加载时,下面的匿名和onload函数没有运行?我错过了一些非常非常基本的东西。 Library.js 只有一行:console.log(
我知道 javascript 是一种客户端语言,但如果实际代码中嵌入的 javascript 代码以某种方式与在控制台上运行的代码不同,我会尝试找到答案。让我用一个例子来解释它: 我想创建一个像 Mi
我如何将这个内联 javascript 更改为 Unobtrusive JavaScript? 谢谢! 感谢您的回答,但它不起作用。我的代码是: PHP js文件 document.getElem
我正在寻找将简单的 JavaScript 对象“转储”到动态生成的 JavaScript 源代码中的最优雅的方法。 目的:假设我们有 node.js 服务器生成 HTML。我们在服务器端有一个对象x。
我是一名优秀的程序员,十分优秀!