将$ .each和$ .getJSON转换为原始javascript

时间:2019-06-06 09:34:46

标签: javascript jquery html css

我正在创建一个Web应用程序,以从GitHub API收集详细信息并将其显示在屏幕上。

我想将$ .getJSON和$ .each转换为原始JavaScript。

我不想在代码中使用jquery的任何部分,因此可以使用Ajax或原始JavaScript。

const execute = () => {
  let uname= document.getElementById('username').value;
  //api for the username
  let apiCall1 = `https://api.github.com/users/${uname}`;
  //api for repository
  let apicall2 = `https://api.github.com/users/${uname}/repos`;
  $.getJSON(apiCall1, (json) => {
    let fullname   = json.name;
    let username   = json.login;
    let aviurl     = json.avatar_url;
    let profileurl = json.html_url;
    let followersnum = json.followers;
    let followingnum = json.following;
    let reposnum     = json.public_repos;

    if(fullname == undefined) { 
      fullname = username; 
    }

    document.getElementById('view').style.display = 'block';
    document.getElementById('result').innerHTML = `
    <h1 class="text-center pt-2">USER DETAILS</h1>
    <div class="row p-3">
      <div class="col-md-3">
        <img class="profile mt-3" src=${aviurl} alt="porfile image">
      </div>
      <div class="col-md-9">
        <h3>FULL NAME: <span>${fullname}</span></h3>
        <h3>USER NAME: <span>${username}</span></h3>
        <h3>PROFILE URL: <a href="${profileurl}"><span>${profileurl}</span></a></h3>
        <h3>FOLLOWERS: <span>${followersnum}</span></h3>
        <h3>FOLLOWING: <span>${followingnum}</span></h3>
        <h3>NUMBER OF REPOSITORIES: <span>${reposnum}</span></h3>
      </div>
    </div>`; 

    let repositories, outhtml;
    $.getJSON(apicall2, function(json){
      repositories = json;   
      outputPageContent();                
    });          

    function outputPageContent() {
      if(repositories.length == 0) {
        outhtml = '<h1>No Repositories!</h1>'; 
      }
      else {
        outhtml = `<h1>LIST OF REPOSITORIES</h1><ul>`;
        $.each(repositories, function(index) {
          outhtml = outhtml + `<li><a href="${repositories[index].html_url}" target="_blank">${repositories[index].name}</a></li>`;
        });
        outhtml = outhtml + '</ul>'; 
      }
      document.getElementById('repo').innerHTML = outhtml;
    }
  })
  .fail(() => { 
    alert("No such username exists!");
    document.getElementById('username').value = "";
    document.getElementById('view').style.display = 'block';
    document.getElementById('result').innerHTML = "Not Available";
    document.getElementById('repo').innerHTML = "Not Available";
  });
};

我无法将代码转换为原始JavaScript。

2 个答案:

答案 0 :(得分:1)

$。getJSON

$.getJSON('https://your.url.com', function(data) {

});

成为:

var request = new XMLHttpRequest();
request.open('GET', 'https://your.url.com', true);

request.onload = function() {
  if (this.status >= 200 && this.status < 400) {
    // Success!
    var data = JSON.parse(this.response);
  } else {
    // error
  }
};

request.send();

fetch('https://your.url.com')
   .then(response => response.json())
   .then(data => // do something with data now)
   .catch(() => // error)

$。each

$.each(collection, (item) => console.log(item));

成为:

collection.forEach(item => console.log(item));

http://youmightnotneedjquery.com/是从jQuery迁移到原始版本的绝佳资源。

答案 1 :(得分:0)

枚举对象时,可以将

$.each替换为带有数组的forEachObject.entries.forEach$.getJSON同样很容易用Fetch API替换。

forEach

const repositoriesArray = [
  "reactjs",
  "angular",
  "foo",
  "bar"
];

repositoriesArray.forEach(repo => {
  console.log(repo)
});

const repositoriesObject = {
  reactjs: {
    company: 'facebook'
  },
  angular: {
    company: 'google'
  }
};

Object.entries(repositoriesObject).forEach(repo => {
  let key = repo[0];
  let value = repo[1];
  
  // Do something with the key/value
  console.log(value.company);
});

获取

$.getJSON(apicall2, function(json){
    repositories = json;   
    outputPageContent();                
});       

例如将成为:

const apicall2 = 'https://jsonplaceholder.typicode.com/users';

fetch(apicall2).then(res => res.json()).then(json => {
  console.log(json[0].name);
});