Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.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
Javascript kitty img的简单抓取_Javascript_Arrays_Api_Fetch Api - Fatal编程技术网

Javascript kitty img的简单抓取

Javascript kitty img的简单抓取,javascript,arrays,api,fetch-api,Javascript,Arrays,Api,Fetch Api,idk知道我对代码做了什么,但昨天这个提取工作正常。我从API中提取了一张小猫图片。 今天当我尝试它不工作时,它说url没有定义。我训练营的朋友也有同样的问题。API出现了一些问题 函数getKitties{ Fetchhttps://api.thecatapi.com/v1/images/search .thenresponse=>{ response.json .thenresponse=>{ console.logresponse } var cat=响应[0]。url; } var i

idk知道我对代码做了什么,但昨天这个提取工作正常。我从API中提取了一张小猫图片。 今天当我尝试它不工作时,它说url没有定义。我训练营的朋友也有同样的问题。API出现了一些问题

函数getKitties{ Fetchhttps://api.thecatapi.com/v1/images/search .thenresponse=>{ response.json .thenresponse=>{ console.logresponse } var cat=响应[0]。url; } var imgcat=document.createElementimg; imgcat.src=cat; var dtag=document.createAttributedata-tag; dtag.value=img kitty; imgcat.setAttributeNodeTag; imgcat.innerHTML= document.body.appendChildimgcat; }
单击我您需要将操作移动到

这是一个使用推荐方法addEventListener和catch以及简化数据属性的版本

document.getElementById'searchKitty'。addEventListener'click',e=>{ 取回https://api.thecatapi.com/v1/images/search' .thenresponse=>response.json .thenresponse=>{ console.logresponse; var cat=响应[0]。url; var imgcat=document.createElementimg; imgcat.src=cat; imgcat.dataset.tag=img kitty; imgcat.setAttributeAt,响应[0]。brides.join | | Cat document.body.appendChildimgcat } .catcherror=>console.logerror.message; } img{ 高度:100px; 保证金:5px; } 点击我
-尝试将您的javascript代码与演示中的代码进行比较。这应该让您了解代码不起作用的原因。您可能应该修复承诺链接-不需要在first-then方法的回调函数中嵌套then方法调用,因为您可以从first-then方法的回调函数返回response.json,然后链接第二个then方法,而不是嵌套它,理想情况下是在那里也应该是一种捕捉方法。@Yousaf谢谢,我错过了。我现在已经简化了代码