亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

API函數被調用兩次導致重復

API函數被調用兩次導致重復

梵蒂岡之花 2022-12-09 16:27:24
我正在嘗試向遠程服務器發送獲取 API 請求。響應非常好,正如我想要的那樣。我正在嘗試將響應存儲在一個表中。但這里的問題是該processRequest()函數被調用了兩次,這會產生重復的結果。我正在使用的警報也顯示了兩次。document.getElementById("ndviHsearch").onclick = function getndviHdata(){   var ndvihconvdataTime=[];   var ndvihStd=[];   var ndvihp25=[];   var ndvihmin=[];   var ndvihmax=[];   var ndvihmedian=[];   var ndvihmean=[];   var ndvihp75=[];   var ndviHfidValue = document.getElementById("ndviHfid").value;   var ndviHstartDateValue = document.getElementById("ndviHstartDate").value;   var ndviHendDateValue = document.getElementById("ndviHendDate").value;   table = document.getElementById("ndviHtable");   const xhr = new XMLHttpRequest();   ndviHstartDateValue = new Date(ndviHstartDateValue).getTime() / 1000;   ndviHendDateValue = new Date(ndviHendDateValue).getTime() / 1000;   xhr.open("GET","https://api.agromonitoring.com/agro/1.0/ndvi/history?polyid="+ndviHfidValue+"&start="+ndviHstartDateValue+"&end="+ndviHendDateValue+"&appid=APIKEY");   xhr.setRequestHeader("Content-Type","application/json");   xhr.send();   xhr.onreadystatechange = processRequest;   function processRequest(e) {     if (xhr.status==200){       response = JSON.parse(xhr.responseText);       alert (response.length);       for (var i=0; i<response.length; i++){         var dt = response[i].dt;         // Unixtimestamp         var unixtimestamp = dt;         // Months array         var months_arr = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];         // Convert timestamp to milliseconds         var date = new Date(unixtimestamp*1000);            var year = date.getFullYear();         var month = months_arr[date.getMonth()];         var day = date.getDate();         var hours = date.getHours();         var minutes = "0" + date.getMinutes();         var seconds = "0" + date.getSeconds();         }    }    
查看完整描述

1 回答

?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

您還需要檢查 readyState 值(xhr.readyState == 4 && xhr.status == 200)

函數 xhr.onreadystatechange = processRequest;將在每次 xhr 狀態更改時執行,您需要檢查是否readyState == 4還有status  == 200,然后執行您的操作。


查看完整回答
反對 回復 2022-12-09
  • 1 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號