简体   繁体   English

如何将数据从json api传递到javascript var

[英]How to pass data from json api to javascript var

Hello I need some help i am new learning so well the question might be a little silly but anyways I am tired of search everywhere and not able to find the answer I need. 您好,我需要一些帮助,因为我刚刚开始学习,所以这个问题可能有点愚蠢,但是无论如何我都厌倦了到处搜索并且无法找到我需要的答案。

So basically I have this json located at http://swapi.co/api/people/1/?format=json and I have this function in javascript: 所以基本上我在http://swapi.co/api/people/1/?format=json上有这个json,并且在javascript中有这个功能:

function get_data_api()
{
 var data = anything_in_http://swapi.co/api/people/1/?format=json

 alert("name_of_json_from_url")
 }

So what I am trying to is to assign to that var data everything cotained in the json URL and then fetched to every tag and show them in an alert. 因此,我要尝试的是将json URL中包含的所有内容分配给该var数据,然后将其提取到每个标签并在警报中显示它们。

Hope it makes sense! 希望有道理!

This is a JavaScript implementation you don't need JQuery 这是不需要JQuery的JavaScript实现

 var getJSON = function(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'json'; xhr.onload = function() { var readyState = xhr.readyState; var status = xhr.status; if (readyState == 4 && status == 200) { callback(null, xhr.response); } else { callback(status); } }; xhr.send(); }; getJSON('http://swapi.co/api/people/1/?format=json', function(err, data) { if (err != null) { alert('You have an error: ' + err); } else { console.log(data); alert('The name from the URL: ' + data.name); } }); 

You can use jQuery http://api.jquery.com/jquery.getjson/ 您可以使用jQuery http://api.jquery.com/jquery.getjson/

var jqxhr = $.getJSON( "http://swapi.co/api/people/1/?format=json", function() {
  console.log( "success" );
})
  .done(function(data) {
    console.log( data.name );
});

This is a possible duplicate of How to get JSON from URL in Javascript? 这可能与如何从Javascript中的URL获取JSON重复 which is the first result on google with keyword "javascript json from url" maybe you were using a wrong keywords for searching 这是在Google上使用关键字“来自url的javascript json”的第一个结果,可能是您在搜索时使用了错误的关键字

Extra info: How to add jQuery to your page Add inside html head <head> </head> the jQuery js file 额外信息:如何将jQuery添加到页面中在html head <head> </head>内添加jQuery js文件

Method 1: Use CDN hosted js file 方法1:使用CDN托管的js文件

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Method 2: Download jquery.min.js then 方法2:然后下载jquery.min.js

<script src="/path/in/your/server/jquery.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM