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

从Promise获取并传递数据的问题:fetch返回值传入AJAX请求失败

问题根因与解决方案

核心问题说明

  • 异步逻辑错误:fetch是异步API,不会阻塞后续代码执行,固定3秒延时不可靠,接口响应速度波动时依然会出现变量为空的问题
  • 语法错误:你提供的代码中setTimeout函数、点击事件回调均缺少闭合括号,会导致整个代码块抛出语法错误无法执行,这是你设置延时后没有任何流程执行的直接原因
  • 不安全的JSON拼接:手动拼接JSON字符串极易出现转义错误,触发后续AJAX请求参数异常

修正方案

直接把AJAX请求放到fetch的成功回调链中,不需要额外设置延时,保证fetch拿到ubicacion的值后再发起AJAX请求,同时修复语法错误、优化JSON生成逻辑:

$("body").on('click', '#MainContent_lnk_actualizar_foto', e => {
    e.preventDefault();
    let Archivo = $('#MainContent_file_foto')[0].files[0];
    let params = new URLSearchParams(location.search);
    let Id_Usuario = params.get('Id_Usuario');
    const datos = new FormData();
    datos.append('imagen', Archivo);
    datos.append('ubicacion', 'perfil');
    let ubicacion = '';

    fetch(`http://192.168.0.37:52456/api/Archivos/`, {
        method: 'POST',
        body: datos
    })
    .then(res => res.json())
    .then(response => {
        ubicacion = response.lugar;
        // fetch拿到结果后直接发起AJAX请求
        return $.ajax({
            type: 'POST',
            url: 'WebService_V_Perfil.asmx/SubirArchivos',
            // 用JSON.stringify生成合法JSON,避免手动拼接的转义错误
            data: JSON.stringify({
                Archivo: ubicacion,
                Id_Usuario: Id_Usuario
            }),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
        });
    })
    .then(result => {
        // AJAX请求成功的回调
        console.log(result);
        console.log(ubicacion);
    })
    .catch(error => {
        // 统一捕获fetch、AJAX所有环节的错误
        console.error('请求出错:', error);
    })
});

可选优化

如果运行环境支持async/await,可以改写为同步写法,逻辑更清晰易维护:

$("body").on('click', '#MainContent_lnk_actualizar_foto', async e => {
    e.preventDefault();
    try {
        let Archivo = $('#MainContent_file_foto')[0].files[0];
        let params = new URLSearchParams(location.search);
        let Id_Usuario = params.get('Id_Usuario');
        const datos = new FormData();
        datos.append('imagen', Archivo);
        datos.append('ubicacion', 'perfil');
        
        // 等待fetch请求完成
        const fetchRes = await fetch(`http://192.168.0.37:52456/api/Archivos/`, {
            method: 'POST',
            body: datos
        });
        const fetchData = await fetchRes.json();
        const ubicacion = fetchData.lugar;
        
        // 等待AJAX请求完成
        const ajaxRes = await $.ajax({
            type: 'POST',
            url: 'WebService_V_Perfil.asmx/SubirArchivos',
            data: JSON.stringify({ Archivo: ubicacion, Id_Usuario }),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
        });
        
        console.log('请求成功', ajaxRes, ubicacion);
    } catch (error) {
        console.error('流程出错:', error);
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:45:02