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

Flutter中如何携带ID、经纬度、日期时间调用考勤API提交数据

实现考勤打卡API提交功能指南

1. 明确API参数规则

先拆解你提供的API示例:
http://localhost/school/api/in-attendance/2?date=2023-11-30&in_time=11:00&lat=1&lng=2

  • 路径中的2是用户ID,需要替换为实际要打卡的用户标识
  • 查询参数要求:
    • date:必须是YYYY-MM-DD格式的当前日期
    • in_time:必须是HH:MM格式的当前24小时制时间
    • lat:精确的纬度数值(支持小数,比如39.9042)
    • lng:精确的经度数值(支持小数,比如116.4074)

2. 生成符合要求的日期时间

需要根据当前系统时间生成指定格式的字符串:

  • 日期:直接截取当前日期的YYYY-MM-DD部分,比如今天是2024-05-20,就生成2024-05-20
  • 时间:提取当前小时和分钟,补零后拼接成HH:MM格式,比如下午2点30分生成14:30

3. 发送请求的代码示例

Python 实现(使用requests库)

import requests
from datetime import datetime

# 配置基础信息
user_id = "2"  # 替换为实际用户ID
api_base_url = "http://localhost/school/api/in-attendance"

# 获取当前日期时间并格式化
current_date = datetime.now().strftime("%Y-%m-%d")
current_time = datetime.now().strftime("%H:%M")

# 模拟获取经纬度(实际场景从设备GPS/定位接口获取)
lat = 39.9042
lng = 116.4074

# 构造请求URL
request_url = f"{api_base_url}/{user_id}?date={current_date}&in_time={current_time}&lat={lat}&lng={lng}"

try:
    # 发送GET请求(若API要求POST则改为requests.post,参数按需调整)
    response = requests.get(request_url)
    response_data = response.json()
    
    # 处理返回结果
    if response_data.get("success"):
        print("打卡成功:", response_data["message"])
    else:
        print("打卡失败:", response_data["message"], "错误码:", response_data["code"])
        if response_data["data"] == "YOU_HAVE_ALREADY_PUNCHED_IN_TODAY":
            print("提示:今日已完成打卡,无需重复提交")
except requests.exceptions.RequestException as e:
    print("网络请求异常:", str(e))

JavaScript 实现(浏览器端)

// 配置基础信息
const userId = "2"; // 替换为实际用户ID
const apiBaseUrl = "http://localhost/school/api/in-attendance";

// 获取当前日期时间并格式化
const now = new Date();
const currentDate = now.toISOString().split('T')[0]; // 生成YYYY-MM-DD格式
const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;

// 模拟获取经纬度(实际场景调用设备定位API)
let lat = 39.9042;
let lng = 116.4074;

// 实际获取定位的逻辑(可选,根据业务需求调整)
navigator.geolocation.getCurrentPosition(
    (position) => {
        lat = position.coords.latitude;
        lng = position.coords.longitude;
        sendAttendanceRequest();
    },
    (error) => {
        console.error("获取定位失败:", error.message);
        sendAttendanceRequest(); // 定位失败仍可尝试提交
    }
);

// 发送请求函数
function sendAttendanceRequest() {
    const requestUrl = `${apiBaseUrl}/${userId}?date=${currentDate}&in_time=${currentTime}&lat=${lat}&lng=${lng}`;
    
    fetch(requestUrl)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log("打卡成功:", data.message);
                // 可添加成功后的UI提示逻辑
            } else {
                console.log("打卡失败:", data.message, "错误码:", data.code);
                if (data.data === "YOU_HAVE_ALREADY_PUNCHED_IN_TODAY") {
                    console.log("提示:今日已打卡,请勿重复操作");
                }
            }
        })
        .catch(error => {
            console.error("网络请求异常:", error);
        });
}

4. 关键注意事项

  • 经纬度获取:实际场景要调用设备的定位API(手机GPS、浏览器navigator.geolocation),确保坐标准确
  • 请求方式:确认API要求的是GET还是POST,示例用的是GET,若为POST需将参数放入请求体
  • 参数校验:严格按照指定格式传递日期时间,格式错误可能直接返回失败
  • 重复打卡处理:当返回YOU_HAVE_ALREADY_PUNCHED_IN_TODAY时,直接提示用户无需重复提交
  • 异常捕获:必须处理网络故障、服务器不可达等情况,给用户明确的错误提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 21:12:52