【问题标题】:Update data using Javascript ajax async failed使用 Javascript ajax 异步更新数据失败
【发布时间】:2019-05-27 07:17:12
【问题描述】:

我正在使用 HTMLjavascriptNodejs 代码来开发 chrome 扩展。 在页面加载时,我调用函数 getBalance() 来获取数据并将其绑定到 HTML 跨度。以下是我的代码:

function getBalance() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://xxx.xxx.xx.xxx:xxxx/getAccount?address=xxxxxxxxxxxxxxxxxxxx', true);
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status >= 200 && request.status < 400) {
        var bal = data.Balance;
        var etherprice = bal / 1000000000000000000;
        document.getElementById("accbal").innerHTML = etherprice;
      } else {
        console.log('error');
      }
    }
    request.send(null);
}

window.addEventListener('load', function load(event){
    getBalance();
});

function sendTransactionBroadcast(result){ 
    var doAjax = function() { 
    $.ajax({ 
    type : "POST", 
    url : "http://xxx.xxx.xx.xxx:xxxx/broadcast",   
    data: JSON.stringify(result), 
    contentType: 'text/plain; charset=UTF-8', 
    success:function(json){ 
      console.log(json);
      getBalance();
    }, 
    error: function() { 
    alert("Error"); 
    } 
    }); 
    } 
    doAjax(); 
    }

sendTransactionBroadcast() 函数在按钮点击时被调用,这个函数有 ajax 异步 POST 调用。执行完成后,如果成功,我想要来自getBalance() 函数的更新数据并将其绑定到跨度。所以,我在 ajax 成功时再次调用它。问题是,如果我设置调试器并逐行调试代码,我会在 span innerHTML 中获得更新的数据。一切顺利。但是,如果我关闭调试器并单击按钮,则跨度 innerHTML 不会在 UI 上发生更改。我不明白为什么?有时它有时会改变,有时不会。 这是 ajax 异步响应问题还是其他问题?如何解决?

manifest.json

{
  "manifest_version": 2,

  "name": "C Wallet",
  "description": "The C Wallet in your browser",
  "version": "1.0",

  "browser_action": {
   "default_icon": "Image/CI_logo-01.png",
   "default_popup": "popup.html"
  },
  "icons": { "16": "Image/CI_logo-01.png",
    "48": "Image/CI_logo-01.png",
   "128": "Image/CI_logo-01.png" 
  },
  "permissions": [
   "activeTab"
   ]
}

【问题讨论】:

  • 乍一看,您的getBalance 函数似乎正在缓存一些值:尝试request.open('GET', 'http://xxx.xxx.xx.xxx:xxxx/getAccount?address=xxxxxxxxxxxxxxxxxxxx&amp;someRandomValue=' + Date.now() , true); 这应该会强制浏览器从服务器而不是浏览器缓存中提取数据
  • 我试过这个,现在我知道在按钮的第一次点击它工作正常。在第二次点击时,它不会得到更新。
  • 您的代码似乎按预期工作!我用伪造的 API 试了一下,效果很好。它还会在后续点击时更新价格
  • @Saroj 你在 Chrome 扩展上用过吗?
  • 不。用简单的 html 和 js 试试吧。

标签: javascript node.js ajax google-chrome-extension get


【解决方案1】:

嗯,我发现了问题。当我使用 HTML button type="submit" 时,页面正在加载并且数据没有根据我的设置进行更改。它正在重置。为了避免页面加载,我使用了button type="button",所有问题都得到了解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多