繁体   English   中英

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

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

您好,我需要一些帮助,因为我刚刚开始学习,所以这个问题可能有点愚蠢,但是无论如何我都厌倦了到处搜索并且无法找到我需要的答案。

所以基本上我在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")
 }

因此,我要尝试的是将json URL中包含的所有内容分配给该var数据,然后将其提取到每个标签并在警报中显示它们。

希望有道理!

这是不需要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); } }); 

您可以使用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 );
});

这可能与如何从Javascript中的URL获取JSON重复 这是在Google上使用关键字“来自url的javascript json”的第一个结果,可能是您在搜索时使用了错误的关键字

额外信息:如何将jQuery添加到页面中在html head <head> </head>内添加jQuery js文件

方法1:使用CDN托管的js文件

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

方法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