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

Wix中如何从API响应获取多字段值并注入文本元素?

如何在Wix中获取汇率API的base、date和rates字段并展示

要同时获取API返回的base、date和rates字段并展示在页面上,你只需要对后端和页面代码做一些小调整,让后端返回完整的所需数据,再在页面中解析并注入到对应的文本元素里。

第一步:修改后端代码,返回完整数据对象

原来的后端代码只返回了单个汇率值,现在我们让它返回包含base、date和目标货币汇率的对象,这样页面能拿到所有需要的信息:

import {fetch} from 'wix-fetch'; 

export function getCurrency(currency, baseCurrency) { 
    const url = 'https://api.fixer.io/latest?base='; 
    let fullUrl = url + baseCurrency + '&symbols=' + currency; 
    return fetch(fullUrl, {method: 'get'}) 
        .then(response => response.json()) 
        .then(json => {
            // 返回包含base、date和目标汇率的对象
            return {
                base: json.base,
                date: json.date,
                rate: json.rates[currency].toString()
            };
        }); 
}

这里我们不再直接返回汇率字符串,而是构建了一个包含三个关键字段的对象,确保页面能获取到API返回的所有必要信息。

第二步:修改页面代码,解析并展示所有数据

现在页面调用getCurrency后会拿到完整的数据对象,你可以把这些数据分别注入到对应的页面文本元素中。假设你已经有展示汇率的#currencyrate元素,另外新增一个展示日期的#currencyDate元素(如果需要单独展示base,也可以添加对应的元素):

import {getCurrency} from 'backend/ArenaApi'; 

export function button1_click(event, $w) { 
    const targetCurrency = $w("#currencysymbol").value;
    const baseCurrency = $w("#baseCurrency").value;
    
    getCurrency(targetCurrency, baseCurrency) 
        .then(currencyData => {
            // 设置汇率文本
            $w("#currencyrate").text = `1 ${currencyData.base} = ${currencyData.rate} ${targetCurrency}`;
            // 设置日期文本(如果有对应的元素)
            $w("#currencyDate").text = `汇率更新日期:${currencyData.date}`;
            // 显示对应的元素
            $w("#currencyrate").show();
            $w("#currencyDate").show();
        })
        // 可选:添加错误处理,提升用户体验
        .catch(error => {
            console.error('获取汇率出错:', error);
            $w("#currencyrate").text = '抱歉,获取汇率失败,请稍后重试';
            $w("#currencyrate").show();
        }); 
}

额外说明

  • 如果你需要单独展示base字段,可以添加一个文本元素(比如#baseCurrencyDisplay),然后设置$w("#baseCurrencyDisplay").text = 基础货币:${currencyData.base};
  • 加入错误处理很重要,能在API请求失败时给用户明确的反馈,避免页面无响应或显示空白。

内容的提问来源于stack exchange,提问作者Shantanu Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:40:10