【问题标题】:How to make function work after another (which contains ajax request)如何使功能接连工作(包含ajax请求)
【发布时间】:2020-09-18 04:38:47
【问题描述】:

我有 2 个功能:首先在页面上加载 svg,然后在某些 svg 中更改某些 <path> 的颜色。

这个函数看起来像:

get_svg_part(category,position,part_name); -- 包含 ajax

svg_part_color(category,position,color,parameter); -- 需要在get_svg_part()之后执行

我有一些情况,我只是加载 svg 而不改变颜色,在另一种情况下,我需要加载 svg 并改变其中的情侣颜色。这就是为什么我没有在ajax 中使用successcomplite。我还需要在页面加载时执行此操作,因此我将所有(2 个函数和调用)放在 jQuery(document).ready() 之前(如果需要此信息)。

我尝试通过$.when.then 来做,但这没有效果:

$.when(get_svg_part('accent','bottom','???? U+1F60A')).then(svg_part_color('accent','bottom','#FF7892',0));

也许我也需要在某种意义上使svg_part_color(); 异步?如果是,那怎么办?

问题:如何让函数一个接一个地工作(包含ajax请求)?

如果这会像这样工作,那就太酷了:

get_svg_part('accent','bottom','???? U+1F60A');
svg_part_color('accent','bottom','#FF7892',0);

$.when(get_svg_part()).then(svg_part_color()); // just set a rule and not execute function here

// or maybe put this rule in svg_part_color() function

更新: get_svg_part 代码:

function get_svg_part(cathegory,position,part_name){ 
   $.ajax({
    		url: "img/icons/parts/"+cathegory+"/"+position+"/"+part_name+".svg",
    		type: 'GET',
    		dataType: 'html',
    		success: function( data ){
    			let rate_block_rated = movie_block.find('.movie_rating.rated'); //rate_block_rated
    			let svg_symbol = rate_block_rated.find(".composite_rate svg ."+cathegory+"."+position);
    			// prepend (insert) data to svg_symbol (accent bottom),
    			// then find inserted svg, and delete svg tag (unwrap path)
    			svg_symbol.prepend(data).find('svg').children().unwrap();

    		}
    });					
};

【问题讨论】:

  • "contains ajax""returns ajax promise" 是两个不同的东西,会影响$.when 的工作方式。需要看更多get_svg_part()的结构

标签: jquery ajax svg .when asynchronous-javascript


【解决方案1】:

只要您的第一个函数返回一个与 ajax 相关的承诺,那么您就可以执行以下操作:

function get_svg_part(a, b, c){  

    // return the jQuery `$.ajax()`, `$.post()`, `$.getJSON()` 
    // or whatever method you are using    
    return $.ajax({/* options */})

} 

用法:

get_svg_part().then(function() { 
   svg_part_color('accent','bottom','#FF7892',0);
})

【讨论】:

    猜你喜欢
    • 2016-10-07
    • 2021-08-30
    • 2013-03-20
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    相关资源
    最近更新 更多