Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将数据从json api传递到javascript变量_Javascript_Json - Fatal编程技术网

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

如何将数据从json api传递到javascript变量,javascript,json,Javascript,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中包含的所有内容分配给该

你好,我需要一些帮助,我是个新手,学得很好,这个问题可能有点傻,但无论如何,我厌倦了到处搜索,无法找到我需要的答案

所以基本上我把这个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-json-from-url”的搜索结果,也许你在搜索时使用了错误的关键字

额外信息:如何将jQuery添加到页面 在jQueryJS文件中添加html头

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

这是一个不需要JQuery的JavaScript实现

var getJSON=function(url,回调){
var xhr=new XMLHttpRequest();
xhr.open('GET',url,true);
xhr.responseType='json';
xhr.onload=函数(){
var readyState=xhr.readyState;
var status=xhr.status;
如果(readyState==4&&status==200){
回调(null,xhr.response);
}否则{
回调(状态);
}
};
xhr.send();
};
getJSON('http://swapi.co/api/people/1/?format=json',
功能(错误、数据){
if(err!=null){
警报(“您有一个错误:”+err);
}否则{
控制台日志(数据);
警报(“URL中的名称:”+data.name);
}

});这对我来说并不清楚,不幸的是,我尝试了复制粘贴在我的函数中运行它,但它没有显示任何东西事实上控制台只显示了一个错误“uncaughtreferenceerror:$未定义”,下面是函数get_data_api(){var jqxhr=$.getJSON(“,function(){console.log(“success”);})(data){console.log(data.name);});}修改了答案以解释如何添加jQuery
<script src="/path/in/your/server/jquery.min.js"></script>