You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AJAX请求后翻译变量有时不显示问题求助

解决AJAX翻译偶尔无输出的问题(字典加载时序问题)

我通过AJAX从数据库获取数据,再用页面初始化时加载的字典对象t做翻译,但有时能正常显示翻译结果,有时却没有内容输出。怀疑是字典文件读取耗时,导致AJAX回调执行时t还没加载完成。相关代码如下:

var json = JSON.parse( response );          // success function
var type_aux=t[json[0].type];
alert("->"+type_aux+"<-");
$('#TYPE_SHOW').html(type_aux); 

解决思路

  • 确保字典加载完成后再发起AJAX请求
    核心是调整异步操作顺序,把数据请求放在字典加载完成的回调里,从根源避免时序问题。
    用jQuery加载字典的示例:

    // 优先加载字典文件
    $.getJSON('你的字典文件路径.json', function(dictData) {
      window.t = dictData;
      // 字典加载完成后,再发起数据库数据请求
      $.ajax({
        url: '你的API接口地址',
        success: function(response) {
          var json = JSON.parse(response);
          var type_aux = t[json[0].type];
          alert("->"+type_aux+"<-");
          $('#TYPE_SHOW').html(type_aux);
        }
      });
    });
    

    原生JS的实现方式:

    const dictXHR = new XMLHttpRequest();
    dictXHR.open('GET', '你的字典文件路径.json');
    dictXHR.onload = function() {
      if (dictXHR.status === 200) {
        window.t = JSON.parse(dictXHR.responseText);
        // 字典就绪后请求数据
        fetch('你的API接口地址')
          .then(res => res.text())
          .then(response => {
            var json = JSON.parse(response);
            var type_aux = t[json[0].type];
            alert("->"+type_aux+"<-");
            document.getElementById('TYPE_SHOW').innerHTML = type_aux;
          });
      }
    };
    dictXHR.send();
    
  • 给AJAX回调加兜底校验
    即使时序控制出现疏漏,也能避免页面空内容,同时快速定位问题:

    var json = JSON.parse( response );
    // 先检查字典是否加载完成
    if (typeof t === 'undefined') {
      alert('字典未加载完成');
      $('#TYPE_SHOW').html('加载中...');
      // 可选:延迟重试请求
      setTimeout(() => { /* 重新执行当前AJAX逻辑 */ }, 500);
      return;
    }
    // 检查当前类型是否存在于字典中
    var type_aux = t[json[0].type];
    if (type_aux === undefined) {
      alert(`字典中没有${json[0].type}对应的翻译项`);
      $('#TYPE_SHOW').html(json[0].type); // 显示原始值替代空内容
    } else {
      alert("->"+type_aux+"<-");
      $('#TYPE_SHOW').html(type_aux);
    }
    
  • 用Promise统一管理异步流程
    适合复杂场景,通过Promise链式调用明确异步操作顺序:

    // 封装字典加载为Promise
    function loadDictionary() {
      return new Promise((resolve, reject) => {
        $.getJSON('你的字典文件路径.json', resolve).fail(reject);
      });
    }
    
    // 封装数据请求为Promise
    function fetchDatabaseData() {
      return new Promise((resolve, reject) => {
        $.ajax({url: '你的API接口地址', success: resolve, error: reject});
      });
    }
    
    // 按顺序执行
    loadDictionary()
      .then(dict => {
        window.t = dict;
        return fetchDatabaseData();
      })
      .then(response => {
        var json = JSON.parse(response);
        var type_aux = t[json[0].type];
        alert("->"+type_aux+"<-");
        $('#TYPE_SHOW').html(type_aux);
      })
      .catch(error => {
        console.error('加载失败:', error);
        $('#TYPE_SHOW').html('加载出错,请稍后重试');
      });
    

内容的提问来源于stack exchange,提问作者pibolito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:45:47