gpt4 book ai didi

javascript - 获取要显示的API数据表单URL

转载 作者:行者123 更新时间:2023-12-03 02:49:44 26 4
gpt4 key购买 nike

我正在尝试构建一个基本工具来通过邮政编码显示某人的国会代表。

我尝试使用的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>







尝试II

好的,我认为我有一个更好的理解,但仍然对以下内容感到困惑,这是我根据您的示例更新的代码并附带一些注释。



<!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 + " ");
});
}


结果将是您的JSON对象。如您所料。

到目前为止,您对以上内容的理解已经足够接近您了。您的麻烦实际上始于理解 $.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=0itemName="item1"
在第二个调用中, i=1itemName="item2"
在第三个调用中, i=2itemName="item3"
因为循环已完成,所以不会再有呼叫。


因此, $.each( array, function(){} )会将函数应用于数组的每个元素。

这意味着您感兴趣的JSON数据将在函数调用的 field变量中,因此在函数执行时:

$("div").append(field+" ");


该代码执行以下操作:


将值“ div”传递给jQuery定位器,该定位器将获取“ div”标记所标识的项的所有实例。
在DIV元素上调用append方法。
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>





附带说明,方法“ getJSON”是一种快捷方式,并非在所有版本的jQuery中都定义。我很难在浏览器中使用此特定方法,因此总是最好使用main方法,在本例中为$ .ajax()。

给其他用户的注意

上面的答案仍然是建议的操作。用户Heck Raiser和我已经开始交换电子邮件,以帮助他进一步理解上述代码。他正在更新他的问题,以反映在我们正在进行的讨论的基础上,他的理解有所增加。这不会更改上面的答案。

Heck Raiser将面临的问题之一是,由于CORS,他的浏览器阻止了JSON响应。我已经向他推荐他从服务器发出JSON请求,并指示他的浏览器改为调用服务器代码。这将使域名保持不变,不会为浏览器引发任何标志,并将允许处理JSON响应而不会出现CORS错误。

Heck Raiser选择使用PHP来实现此功能的后端实现,但是所使用的语言与该技术无关。重要的是:要解决CORS错误,必须调用与jQuery当前运行所在页面位于同一域的页面。

enter image description here

关于javascript - 获取要显示的API数据表单URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47931850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com