简体   繁体   English

Ajax调用,函数回调,javascript

[英]Ajax call, function callback, javascript

I have function like that 我有这样的功能

function cryptChange(cr){
        var url = 'https://min-api.cryptocompare.com/data/dayAvg?fsym=' + cr + '&tsym=PLN';
        console.log(url);      // it's just for testing in console

};
cryptChange('LTC');
cryptChange('BTC');

As you can see this code is working fine with URL of AJAX call with JSON data, returning valid URL. 如您所见,此代码与带有JSON数据的AJAX调用的URL正常工作,返回有效的URL。 Want to make something like that, but in shorter version, I have many lines of code like the ones below and I do want to get less 想要做类似的事情,但是在较短的版本中,我有很多类似下面的代码行,但我希望减少代码行数

$.getJSON('https://min-api.cryptocompare.com/data/dayAvg?fsym=BTC&tsym=PLN', function(btc2){
    $('#tt-11').html(btc2.PLN.toFixed(2)); //its passed into html block
});
$.getJSON('https://min-api.cryptocompare.com/data/dayAvg?fsym=BCH&tsym=PLN', function(bch2){
        $('#tt-12').html(bch2.PLN.toFixed(2));
    });

And now I want to mix that cryptChange function with AJAX call to pass parameter for callback and use that in $ ('#tt-11').html ( btc2 here <==.PLN.toFixed (2); 现在,我想将cryptChange函数与AJAX调用混合使用,以传递用于回调的参数,并在$('#tt-11')。html中使用它( btc2 在这里 <==。PLN.toFixed(2);

Is that clearer guys now? 现在更清楚了吗?

Define a function that takes all the varying parts as parameters. 定义一个将所有不同部分作为参数的函数。

function getCrypt(from, to, id) {
    $.getJSON('https://min-api.cryptocompare.com/data/dayAvg', {
        fsym: from,
        tsym: to
    }, function(result){
    $('#' + id).html(result[to].toFixed(2));
});

You can then do: 然后,您可以执行以下操作:

getCrypt('BTC', 'PLN', 'tt-11');
getCrypt('BCH', 'PLN', 'tt-12');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM