【问题标题】:how to write $.get(url, function(data) in pure JavaScript [duplicate]如何在纯 JavaScript 中编写 $.get(url, function(data) [重复]
【发布时间】:2019-03-20 10:31:40
【问题描述】:

这是我想要弄清楚的。 如何在纯 JavaScript 中编写 $.get(url,function(data) { code };。

function newimage(keyword){
  if(!ACCESS_KEY){
    alert("Please update your access key");
    return;
  }
  var url = `https://api.unsplash.com/search/photos?query=${keyword}&per_page=20&orientation=landscape&client_id=${ACCESS_KEY}`;
  $.get(url,function(data){
    var picture = data.results[0];
    var picture_url = picture.urls.raw;
    var photo_by_name = picture.user.name;
    var photo_by_url = picture.user.links.html;
    setCookie("picture",picture_url,0.5);
    setCookie("photo-by-name",photo_by_name,0.5);
    setCookie("photo-by-url",photo_by_url,0.5);
    picInterest.innterHTML = `${keyword}`;
    photoBy.innterHTML = `${photoByUrl}`;
    photoBy.setAttribute('html', photoByUrl);
    document.querySelector("body").style.backgroundImage = `url(${pictureUrl})`;
    pictureOption.style.display = "block";
  });
}

【问题讨论】:

标签: javascript jquery


【解决方案1】:

你可以像这样使用 fetch api:

fetch(url).then(res => res.json()).then(data => {
  //whatever you want
})

【讨论】:

  • 谢谢。我是编码新手,还没有学习 javascript 的所有不同语法。所以,我不知道有一种不同的方法来解决这个问题。不过谢谢你指出来。
【解决方案2】:

你可以用这个:

var url = `https://api.unsplash.com/search/photos?query=${keyword}&per_page=20&orientation=landscape&client_id=${ACCESS_KEY}`;
var xhr = new XMLHttpRequest ();
xhr.open ( "GET", url);
xhr.onreadystatechange = function ()
{
  if ( xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200)
  {
    // Here you handle the response
    // Result text will be accessible at xhr.responseText
  }
}
xhr.send ();

【讨论】:

  • 感谢您表明我应该使用 AJAX 来执行此操作。
猜你喜欢
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 2011-05-18
  • 2011-09-07
  • 2012-04-03
  • 1970-01-01
  • 2014-02-18
相关资源
最近更新 更多