/** * IP 服务客户端 (ES5 兼容) * @version 1.0.0 */ var IPService = (function() { 'use strict'; function IPService(baseURL) { this.baseURL = baseURL || ''; } /** * 获取 IP 地址 * @param {Function} callback - 回调函数 callback(error, data) */ IPService.prototype.getIP = function(callback) { var self = this; this._request(this.baseURL + '/api/get-ip', function(err, data) { if (callback) { callback(err, data); } }); }; /** * 获取 IP + 地理位置信息 * @param {Function} callback - 回调函数 callback(error, data) */ IPService.prototype.getIPInfo = function(callback) { var self = this; this._request(this.baseURL + '/api/get-ip-info', function(err, data) { if (callback) { callback(err, data); } }); }; /** * 内部请求方法 * @private */ IPService.prototype._request = function(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.setRequestHeader('Accept', 'application/json'); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { try { var data = JSON.parse(xhr.responseText); callback(null, data); } catch (e) { callback(new Error('JSON parse failed'), null); } } else { callback(new Error('HTTP ' + xhr.status), null); } }; xhr.onerror = function() { callback(new Error('Network error'), null); }; xhr.ontimeout = function() { callback(new Error('Request timeout'), null); }; xhr.timeout = 10000; // 10 秒超时 xhr.send(); }; return IPService; })(); // 导出到全局作用域 if (typeof window !== 'undefined') { window.IPService = IPService; } // 导出为 CommonJS 模块 if (typeof module !== 'undefined' && module.exports) { module.exports = IPService; }