weixin_33701294 2014-03-17 16:16 采纳率: 0%
浏览 17

jQuery功能的承诺

I'm trying to make global ajax handler. so first let me show you the function

    var data = {
       test : 1
    }
    $.when( $.ajax({
        type: 'POST',
        url: ajaxurl,
        data : data,
        dataType: "json",
        success: function(data) {
            console.log('first me')
        }
        })
    ).then(function( data, textStatus, jqXHR ) {
        console.log('then me')
    });

this way it works. and outputs

first me

then me

But I want this ajax to be a function So this is how I'm trying to make it.

    var data = {
       test : 1
    }
    $.when(globalAjax(data)).then(function( data, textStatus, jqXHR ) {
        console.log('then me')
    });

    function globalAjax(data) {
           $.ajax({
        type: 'POST',
        url: ajaxurl,
        data : data,
        dataType: "json",
        success: function(data) {
            console.log('first me')
        }
        })

    }

this way console outputs then me and then first me.

How to ask to wait ajax inside a function?

  • 写回答

3条回答 默认 最新

  • weixin_33720186 2014-03-17 16:20
    关注
     function globalAjax(data) {
         return $.ajax({
            type: 'POST',
            url: ajaxurl,
            data : data,
            dataType: "json",
            success: function(data) {
                console.log('first me')
               }
            });
        }
    

    you need to return a promise from your function.

    $.ajax({
            type: 'POST',
            url: ajaxurl,
            data : data,
            dataType: "json",
            success: function(data) {
                console.log('first me')
            }
            }).then(function( data, textStatus, jqXHR ) {
            console.log('then me')
            });
    

    You dont need when $.ajax already returns a promise.

    评论

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python