JavaScript HTTP请求失败

编程入门 行业动态 更新时间:2024-10-09 12:28:32
本文介绍了JavaScript HTTP请求失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人可以看看下面的代码来帮助我弄清楚我在做什么错吗?我收到此错误

Could anybody take a look at below code help me to figure out what I am doing wrong ? I am getting this error

错误XMLHttpRequest {readyState:1,超时:0,带有凭据: false,上传:XMLHttpRequestUpload,responseURL:" ...}

error XMLHttpRequest {readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, responseURL: ""…}

当我试图向NASA图像库请求获取图像时.

when I am trying to make a request to NASA image galary to fetch a image..

HTML:

<img id="map" src="" alt="image from NASA">

JS:

var get = function(url){ return new Promise(function(resolve,reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4 && xhr.status == 200){ var result = xhr.responseText; result = JSON.parse(result); resolve(result); }else { reject(xhr); } } xhr.open("GET",url,true); xhr.send(null); }) } get('api.nasa.gov/planetary/apod?api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo' ) .then(function(response){ console.log("success",response); document.getElementById('map').src = response.url; }) .catch(function(err){ console.log('error',err) })

推荐答案

您的else语句放置在错误的位置

Your else statement is in the wrong place

ajax请求通过这些不同的状态

The ajax request goes thru these different states

State Description 0 The request is not initialized 1 The request has been set up 2 The request has been sent 3 The request is in process 4 The request is complete

readyState事件将随着这些状态的改变而触发,这就是为什么我们检查第四个状态是否是在请求完成后触发回调的状态,并获得返回的数据.

The readyState event will fire as these states change, which is why we check to see that the fourth state is the one triggering the callback, when the request is complete, and we have the returned data.

您正在使用else语句,该语句实际上会在1或除4之外的任何状态上触发,但是1是第一个readyState,当首次设置请求时,您必须等待直到到达第四个readyState

You are using an else statement that will fire on 1, or any state except 4 really, but 1 is the first readyState, when the request is first set up, you have to wait until it reaches the fourth readyState

var get = function(url){ return new Promise(function(resolve,reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4) { if (xhr.status == 200) { var result = xhr.responseText; result = JSON.parse(result); resolve(result); }else { reject(xhr); } } } xhr.open("GET",url,true); xhr.send(null); }) }

FIDDLE

更多推荐

JavaScript HTTP请求失败

本文发布于:2023-11-26 19:18:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634861.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JavaScript   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!