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

时间:2017-12-21 19:50:00

标签: javascript jquery json api

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

我尝试使用的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网址获取数据的原因

$.each(results, function(i, field){ - 我不确定这是做什么的,但我认为这会显示&#39;结果&#39;

的字段

$("div").append(field + " "); - 这将在空<div>

中显示数据

完整 index.php 代码

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;

ATTEMPT II

好吧我觉得我有更好的理解,但我仍然对下面的一些内容感到困惑,我的更新代码基于你的样本和一些笔记。

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;

ATTEMPT III

更新了新的评论和问题。

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

你很亲密。

首先解释一下如何解释函数调用,让我帮忙。

$(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( results, function(i,field){...} );的调用会执行以下操作。它遍历结果对象中的每个项目,然后为每个项目调用一次该函数。函数中的第一个参数(i)是结果数组中的索引,第二个参数(field)是实际项目本身。

例如,假设我有以下代码:

var exampleData = ["item1","item2","item3"];
$.each( exampleData, function( i, itemName ){ ... } );

在对function(i, itemName){...}块的每次调用中,我将看到以下内容:

  1. 在第一个电话中,i=0itemName="item1"
  2. 在第二个电话中,i=1itemName="item2"
  3. 在第三个电话中,i=2itemName="item3"
  4. 没有第四次调用,因为循环已完成。
  5. 因此,$.each( array, function(){} )会将函数应用于数组的每个元素。

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

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

    代码执行以下操作:

    1. 将值“div”传递给jQuery定位器,该定位器获取由“div”标记标识的所有项目实例。
    2. 在DIV元素上调用append方法。
    3. field值和空格添加到元素内容的末尾。
    4. 为了理解发生了什么,我建议使用更少的匿名函数,并使用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请求,并指示他的浏览器调用服务器代码。这将保持域名相同,不会引发浏览器的任何标志,并允许在没有CORS错误的情况下处理JSON响应。

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

      enter image description here