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

如何在Odoo JavaScript及通用JS中从URL获取JSON数据?代码求助

问题1:如何在Odoo JavaScript中从URL获取JSON数据?

在Odoo的JavaScript环境里,你有两种靠谱的方式来获取JSON数据,优先推荐用Odoo封装的工具,它会自动处理CSRF令牌、会话验证这些容易踩坑的细节:

方法1:用Odoo内置的odoo.http模块

Odoo提供了odoo.http.get和odoo.http.post方法,专门用来和Odoo后端或者经过代理的外部API通信:

// 示例:请求自定义后端端点或代理后的外部API
odoo.http.get('/your/custom/endpoint', {
    params: {
        key1: 'value1',
        key2: 'value2'
    }
}).then(function(response) {
    // 处理返回的JSON数据
    console.log('获取到的数据:', response.data);
}).catch(function(error) {
    console.error('请求出错:', error);
});

方法2:用原生fetch API

如果是请求允许跨域的外部API,可以直接用fetch,但要注意浏览器的CORS限制:

fetch('https://api.example.com/data.json', {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
}).then(response => response.json())
  .then(data => console.log('获取到的数据:', data))
  .catch(error => console.error('请求失败:', error));

小贴士:如果外部API不允许你的Odoo域名跨域访问,直接前端请求会失败,这时得通过Odoo后端做个代理控制器,让后端去请求外部API再把数据返回给前端。


问题2:代码排查与修复

看你提供的代码,有几个明显的问题导致拿不到数据,我帮你梳理并修正:

存在的问题:

  1. API URL不完整:var api = "http://api.openweath..." 没写完完整的OpenWeatherMap API地址,根本发不出有效请求。
  2. 缺请求逻辑:你只定义了纬度、经度、API密钥和半截URL,但完全没写发起HTTP请求的代码。
  3. 多余参数:showPosition里的http参数没用,navigator.geolocation.getCurrentPosition只会把position对象传给回调函数。
  4. 跨域隐患:直接在前端请求OpenWeatherMap的HTTP API,如果你的Odoo是HTTPS环境,会触发混合内容错误;就算是HTTP,也可能因为CORS限制请求失败。

修正后的前端直接请求示例(需API允许跨域):

var GetLocation = function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

function showPosition(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    var app_id = '6784429f5eff661309aaa5280a143f97';
    // 补全完整的OpenWeatherMap API URL,这里以获取当前天气为例
    var apiUrl = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${app_id}&units=metric`;

    // 发起请求并处理响应
    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error(`请求失败,状态码:${response.status}`);
            }
            return response.json();
        })
        .then(weatherData => {
            console.log('获取到的天气数据:', weatherData);
            // 这里可以加代码把数据展示到页面上,比如更新DOM元素
        })
        .catch(error => {
            console.error('获取天气数据出错:', error);
            alert('无法获取天气数据,请检查网络或API配置');
        });
}

更稳妥的方案:通过Odoo后端代理请求(解决跨域问题)

如果前端直接请求失败,建议在Odoo模块里建个代理控制器:

  1. 在模块的controllers目录下创建weather_proxy.py:
from odoo import http
import requests

class WeatherProxy(http.Controller):
    @http.route('/weather/proxy', type='json', auth='user')
    def weather_proxy(self, lat, lon, app_id):
        api_url = f"http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={app_id}&units=metric"
        try:
            response = requests.get(api_url)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            return {'error': str(e)}
  1. 前端修改为请求这个代理端点:
function showPosition(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    var app_id = '6784429f5eff661309aaa5280a143f97';

    odoo.http.get('/weather/proxy', {
        params: {
            lat: lat,
            lon: lon,
            app_id: app_id
        }
    }).then(function(response) {
        if (response.data.error) {
            console.error('代理请求出错:', response.data.error);
            alert('获取天气数据失败');
        } else {
            console.log('天气数据:', response.data);
            // 处理数据
        }
    }).catch(function(error) {
        console.error('请求代理端点失败:', error);
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:23:29