【问题标题】:Convert Array to Query string in Meteor在 Meteor 中将数组转换为查询字符串
【发布时间】:2014-09-09 04:30:24
【问题描述】:

我正在尝试从 Echonest 获取艺术家个人资料。我需要在查询字符串中有一个名为“bucket”的参数多次。我正在尝试使用包含我传递的对象的数组来设置它。这可以在数组中传递吗?

我有这个:

bucket:['biographies', 'images', 'artist_location', 'urls'];

我想要这个:

bucket=biographies&bucket=images&bucket=artist_location&bucket=urls

客户:

getArtistProfile = function(artistName){
    var params = {
        format:'json',
        bucket:['biographies', 'images', 'artist_location', 'urls'],
        name:artistName
    };

     Meteor.call('getEchoNestData', params, function(error, result) {
        if (error)
            console.warn(error);
        else
            console.log(result);
    });
};

服务器方法:

getEchoNestData:function(type, params){
    check(type, String);

    params.api_key = Meteor.settings.echonest.apiKey;

    var result = HTTP.get('http://developer.echonest.com/api/v4/artist/profile' + type, {timeout:5000, params:params});
    return result;
 }

【问题讨论】:

  • 我认为没有一种方便的方法可以做到这一点。我只会写一个 for 循环或使用 _.reduce 或其他东西。

标签: javascript meteor query-string


【解决方案1】:

我可能误解了您的问题,但您似乎在问如何动态构建一组查询字符串参数。你可以有一个像这样的简单助手:

function getParams( arr ) {
    var params = [];

    for ( i = 0; i < arr.length; ++i ) {
        params.push( 'bucket=' + arr[ i ] );
    }

    return params.join( '&' );
}

并像这样传入您的参数值数组:

var params = getParams( bucket );

http://jsfiddle.net/7vaLcjxs/

【讨论】:

    猜你喜欢
    • 2010-11-25
    • 2020-11-21
    • 2013-07-11
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    相关资源
    最近更新 更多