homeGPSError = result.data.debug_info.failure_reason || result.message || 'GPS定位失败'; } else { homeGPSError = 'GPS定位请求失败'; } requestCityByIP(); } }, error: function(xhr, status, error){ console.error('GPS定位请求失败:', status, error); homeGPSError = 'GPS定位请求失败: ' + (error || status); requestCityByIP(); } }); } function requestCityByIP() { // 防止重复调用 if (homeIPLocating) { console.log('⚠️ IP定位正在进行中,跳过重复调用'); return; } homeIPLocating = true; // 先获取前端真实客户端IP(多个备用服务) var clientIP = ''; // IP获取服务列表(多个备用服务) // IP获取服务列表(已移除api.ipify.org,因为该服务已不可用) var ipServices = [ { name: 'ip.sb', url: 'https://api.ip.sb/ip', parser: function(data) { return typeof data === 'string' ? data.trim() : null; }, dataType: 'text' }, { name: 'ipapi.co', url: 'https://ipapi.co/json/', parser: function(data) { return data && data.ip ? data.ip : null; }, dataType: 'json' }, { name: 'httpbin', url: 'http://httpbin.org/ip', parser: function(data) { return data && data.origin ? data.origin.split(',')[0].trim() : null; }, dataType: 'json' }, { name: 'ip-api.com', url: 'http://ip-api.com/json/?fields=query', parser: function(data) { return data && data.query ? data.query : null; }, dataType: 'json' } ]; // 尝试获取IP(依次尝试各个服务) var tryGetIP = function(index) { if (index >= ipServices.length) { // 所有服务都失败,使用服务器IP console.warn('所有IP获取服务都失败,使用服务器IP'); doRequestCityByIP(''); return; } var service = ipServices[index]; var dataType = service.dataType || 'json'; console.log('尝试IP获取服务 ' + (index + 1) + '/' + ipServices.length + ' (' + service.name + '): ' + service.url); $.ajax({ url: service.url, type: 'GET', dataType: dataType, timeout: 3000, success: function(response) { var ip = service.parser(response); if (ip && /^(\d{1,3}\.){3}\d{1,3}$/.test(ip)) { // 验证IP格式(简单验证IPv4) clientIP = ip; console.log('✓ 获取到客户端真实IP:', clientIP, '(来源: ' + service.name + ')'); doRequestCityByIP(clientIP); } else { // IP格式无效,尝试下一个服务 console.warn('✗ IP格式无效:', ip, '尝试下一个服务'); tryGetIP(index + 1); } }, error: function(xhr, status, error) { // 请求失败,尝试下一个服务 console.warn('✗ IP获取服务失败 (' + service.name + '):', status, error, '尝试下一个服务'); tryGetIP(index + 1); } }); }; // 从第一个服务开始尝试 tryGetIP(0); } // 执行IP定位请求 function doRequestCityByIP(clientIP) { var url = '/index.php?g=Home&m=LocationApi&a=getCityByIP'; if (clientIP) { url += '&ip=' + encodeURIComponent(clientIP); } $.ajax({ url: url, type: 'GET', dataType: 'json', timeout: 5000, success: function(result){ homeIPLocating = false; // 重置标志 console.log('IP定位结果:', result); if (result && result.success && result.data && result.data.city_id) { // 检查是否是回退到默认城市 if (result.data.is_fallback) { console.warn('IP定位失败,已回退到默认城市:', result.data.fallback_reason); } updateCityDisplay(result.data, 'ip'); } else { console.warn('IP定位失败,检查手动选择'); checkManualCity(); } }, error: function(xhr, status, error){ homeIPLocating = false; // 重置标志 console.error('IP定位请求失败:', status, error); checkManualCity(); } }); } // 检查手动选择的城市(从Cookie或Session) function checkManualCity() { // 先检查Cookie中的手动选择 var cookieCityId = getCookie('city_id'); if (cookieCityId) { console.log('发现Cookie中的城市ID:', cookieCityId); // 验证城市是否存在,如果存在则使用 $.ajax({ url: '/index.php?g=Home&m=LocationApi&a=getDefaultCity', type: 'GET', dataType: 'json', timeout: 3000, success: function(result){ // 如果有Cookie城市,先尝试获取该城市信息 if (result && result.success) { // 使用Cookie城市或默认城市 updateCityDisplay(result.data, 'manual'); } else { requestDefaultCity(); } }, error: function(){ requestDefaultCity(); } }); } else { // 没有手动选择,使用默认城市 requestDefaultCity(); } } // 获取Cookie值 function getCookie(name) { var value = "; " + document.cookie; var parts = value.split("; " + name + "="); if (parts.length === 2) { return parts.pop().split(";").shift(); } return null; } function requestDefaultCity() { $.ajax({ url: '/index.php?g=Home&m=LocationApi&a=getDefaultCity', type: 'GET', dataType: 'json', timeout: 5000, success: function(result){ console.log('默认城市结果:', result); if (result && result.success && result.data && result.data.city_id) { updateCityDisplay(result.data, 'default'); } else { console.error('获取默认城市失败:', result); applyHomeSubstationStatus(null, result && result.message ? result.message : '无法获取城市信息'); } }, error: function(xhr, status, error){ console.error('默认城市请求失败:', status, error); applyHomeSubstationStatus(null, '无法获取城市信息'); } }); } function updateCityDisplay(locationData = null, method = 'ip') { if (!locationData || !locationData.city_id || !locationData.city_name) { console.warn('updateCityDisplay: 数据不完整', locationData); return; } // 获取定位类型(location_type或从source解析) var locationType = locationData.location_type || ''; if (!locationType && locationData.source) { var sourceParts = locationData.source.split(':'); if (sourceParts.length >= 2) { locationType = sourceParts[1]; // ip2region, gaode, baidu等 } } // 如果还是没有,尝试从debug_info获取 if (!locationType && locationData.debug_info && locationData.debug_info.location_type) { locationType = locationData.debug_info.location_type; } homeCurrentLocation = { city_id: parseInt(locationData.city_id), city_name: locationData.city_name, province_name: locationData.province_name || '', method: method || 'ip', location_type: locationType || '', source: locationData.source || '', // 保存调试信息 client_ip: locationData.client_ip || (locationData.debug_info && locationData.debug_info.ip) || '', debug_info: locationData.debug_info || {}, is_fallback: locationData.is_fallback || false, fallback_reason: locationData.fallback_reason || '' }; console.log('更新城市显示:', homeCurrentLocation); // 更新页面上的城市显示 const cityName = homeCurrentLocation.city_name; const provinceName = homeCurrentLocation.province_name; const cityElements = document.querySelectorAll('.current-city, #changeCity-current-city'); cityElements.forEach(el => { if (el) el.textContent = cityName; }); const provinceElements = document.querySelectorAll('.province-info, #changeCity-province-info'); provinceElements.forEach(el => { if (el) el.textContent = provinceName ? (provinceName + ' • 当前城市') : cityName; }); // 更新弹窗中的信息(如果弹窗已打开) updateHomeLocationInfoFields(); // 获取分站状态 if (homeCurrentLocation.city_id > 0) { homeSubstationStatusCache = null; homeSubstationStatusMessage = '检测中…'; applyHomeSubstationStatus(null, homeSubstationStatusMessage); fetchHomeSubstationStatus(homeCurrentLocation.city_id); } else { applyHomeSubstationStatus(null, '城市ID无效'); } } function fetchHomeSubstationStatus(cityId) { $.getJSON('/index.php?g=Wap&m=LocationApi&a=getSubstationStatus&city_id=' + encodeURIComponent(cityId), function(res){ if (res && res.success && res.data) { homeSubstationStatusCache = res.data; homeSubstationStatusMessage = ''; applyHomeSubstationStatus(homeSubstationStatusCache); } else { homeSubstationStatusCache = null; homeSubstationStatusMessage = res && res.message ? res.message : '无法获取分站状态'; applyHomeSubstationStatus(null, homeSubstationStatusMessage); } }).fail(function(){ homeSubstationStatusCache = null; homeSubstationStatusMessage = '无法获取分站状态'; applyHomeSubstationStatus(null, homeSubstationStatusMessage); }); } function getHomeLocationMethodText() { if (!homeCurrentLocation) { return '检测中…'; } // 获取定位方式和定位类型 var method = homeCurrentLocation.method || ''; var locationType = homeCurrentLocation.location_type || ''; var source = homeCurrentLocation.source || ''; var libraryMismatch = homeCurrentLocation.library_mismatch || false; var configuredLibrary = homeCurrentLocation.configured_library || ''; // 如果locationType为空,尝试从source解析 if (!locationType && source) { var sourceParts = source.split(':'); if (sourceParts.length >= 2) { locationType = sourceParts[1]; // ip2region, gaode, baidu等 } } var methodMap = { gps: 'GPS定位', wechat: '微信定位', ip: 'IP定位', manual: '手动选择', cache: '缓存定位', default: '默认城市', server: '服务器位置' }; var methodText = methodMap[method] || 'IP定位'; // 如果是IP定位,必须显示定位类型(本地、百度、高德等) if (method === 'ip') { var typeMap = { 'ip2region': '本地', 'gaode': '高德', 'baidu': '百度', 'tencent': '腾讯', 'free': '免费API' }; // 如果配置的库和实际使用的库不一致,使用配置的库显示,但标记为备用 if (libraryMismatch && configuredLibrary) { var configuredType = configuredLibrary === 'ip2region' ? '本地' : (typeMap[configuredLibrary] || configuredLibrary); methodText = 'IP定位(' + configuredType + '备用)'; } else if (locationType && typeMap[locationType]) { methodText = 'IP定位(' + typeMap[locationType] + ')'; } else if (locationType) { methodText = 'IP定位(' + locationType + ')'; } else { methodText = 'IP定位(未知)'; } } return methodText; } function updateHomeLocationInfoFields() { // 只在弹窗打开时更新(弹窗中的元素) var methodSpan = document.querySelector('[data-home-info="method"]'); var typeSpan = document.querySelector('[data-home-info="type"]'); var citySpan = document.querySelector('[data-home-info="city"]'); var ipSpan = document.querySelector('[data-home-info="ip"]'); var debugInfoDiv = document.getElementById('home-debug-info'); if (methodSpan) { var methodText = getHomeLocationMethodText(); methodSpan.textContent = methodText; } if (typeSpan) { var locationType = ''; if (homeCurrentLocation) { // 优先使用location_type var typeValue = homeCurrentLocation.location_type || ''; // 如果location_type为空,尝试从source解析 if (!typeValue && homeCurrentLocation.source) { var sourceParts = homeCurrentLocation.source.split(':'); if (sourceParts.length >= 2) { typeValue = sourceParts[1]; // ip2region, gaode, baidu等 } } // 如果还是没有,尝试从debug_info获取 if (!typeValue && homeCurrentLocation.debug_info && homeCurrentLocation.debug_info.location_type) { typeValue = homeCurrentLocation.debug_info.location_type; } if (typeValue) { var typeMap = { 'ip2region': '本地', 'gaode': '高德', 'baidu': '百度', 'tencent': '腾讯', 'free': '免费API' }; locationType = typeMap[typeValue] || typeValue; } else if (homeCurrentLocation.method === 'ip') { locationType = '未知'; } else { locationType = '-'; } } else { locationType = '检测中…'; } typeSpan.textContent = locationType; } if (citySpan) { var cityText = homeCurrentLocation && homeCurrentLocation.city_name ? homeCurrentLocation.city_name : '检测中…'; citySpan.textContent = cityText; } // 显示获取的IP地址 if (ipSpan) { var ipText = ''; if (homeCurrentLocation) { ipText = homeCurrentLocation.client_ip || (homeCurrentLocation.debug_info && homeCurrentLocation.debug_info.ip) || '未获取'; // 如果是本地IP,标记 if (ipText === '127.0.0.1' || ipText.startsWith('192.168.') || ipText.startsWith('10.') || ipText.startsWith('172.')) { ipText += ' (本地/内网)'; } } else { ipText = '检测中…'; } ipSpan.textContent = ipText; } // 显示调试信息 if (debugInfoDiv) { if (homeCurrentLocation) { debugInfoDiv.style.display = 'block'; // GPS状态 var gpsStatusSpan = debugInfoDiv.querySelector('[data-home-info="gps-status"]'); if (gpsStatusSpan) { if (homeCurrentLocation.method === 'gps' && !homeCurrentLocation.is_fallback) { gpsStatusSpan.textContent = '成功'; gpsStatusSpan.style.color = '#28a745'; } else if (homeGPSError) { gpsStatusSpan.textContent = '失败'; gpsStatusSpan.style.color = '#dc3545'; } else { gpsStatusSpan.textContent = '未使用'; gpsStatusSpan.style.color = '#6c757d'; } } // GPS失败原因 var gpsErrorSpan = debugInfoDiv.querySelector('[data-home-info="gps-error"]'); if (gpsErrorSpan) { var gpsError = homeGPSError || (homeCurrentLocation.debug_info && homeCurrentLocation.debug_info.failure_reason) || ''; if (gpsError) { gpsErrorSpan.textContent = gpsError; gpsErrorSpan.style.color = '#dc3545'; } else { gpsErrorSpan.textContent = '-'; } } // IP定位状态 var ipStatusSpan = debugInfoDiv.querySelector('[data-home-info="ip-status"]'); if (ipStatusSpan) { if (homeCurrentLocation.method === 'ip') { ipStatusSpan.textContent = homeCurrentLocation.is_fallback ? '失败(已回退)' : '成功'; ipStatusSpan.style.color = homeCurrentLocation.is_fallback ? '#dc3545' : '#28a745'; } else { ipStatusSpan.textContent = '未使用'; ipStatusSpan.style.color = '#6c757d'; } } // IP失败原因 var ipErrorSpan = debugInfoDiv.querySelector('[data-home-info="ip-error"]'); if (ipErrorSpan) { var ipError = ''; // 优先显示详细的错误信息 if (homeCurrentLocation.debug_info && homeCurrentLocation.debug_info.ip_location_error) { var errorInfo = homeCurrentLocation.debug_info.ip_location_error; if (errorInfo.error_message) { ipError = errorInfo.error_message; if (errorInfo.error_code) { ipError = '[' + errorInfo.error_code + '] ' + ipError; } } } else if (homeCurrentLocation.ip_location_error) { var errorInfo = homeCurrentLocation.ip_location_error; if (errorInfo.error_message) { ipError = errorInfo.error_message; if (errorInfo.error_code) { ipError = '[' + errorInfo.error_code + '] ' + ipError; } } } else if (homeCurrentLocation.fallback_reason) { ipError = homeCurrentLocation.fallback_reason; } else if (homeCurrentLocation.is_fallback) { ipError = '定位失败,已回退默认城市'; } if (ipError) { ipErrorSpan.textContent = ipError; ipErrorSpan.style.color = '#dc3545'; ipErrorSpan.style.wordBreak = 'break-word'; } else { ipErrorSpan.textContent = '-'; } } // Source var sourceSpan = debugInfoDiv.querySelector('[data-home-info="source"]'); if (sourceSpan) { sourceSpan.textContent = homeCurrentLocation.source || '-'; } // 是否回退 var isFallbackSpan = debugInfoDiv.querySelector('[data-home-info="is-fallback"]'); if (isFallbackSpan) { isFallbackSpan.textContent = homeCurrentLocation.is_fallback ? '是' : '否'; isFallbackSpan.style.color = homeCurrentLocation.is_fallback ? '#dc3545' : '#28a745'; } } else { debugInfoDiv.style.display = 'none'; } } } function applyHomeSubstationStatus(info, message) { var statusSpan = document.querySelector('#home-substation-status'); var btnHolder = document.querySelector('#home-substation-holder'); var systemSpan = document.querySelector('[data-home-info="system"]'); var cityEnableSpan = document.querySelector('[data-home-info="city-enable"]'); var domainSpan = document.querySelector('[data-home-info="domain"]'); updateHomeLocationInfoFields(); if (!statusSpan || !btnHolder) { return; } btnHolder.innerHTML = ''; if (info) { if (systemSpan) { systemSpan.textContent = info.system_enabled ? '已启用' : '未启用'; } if (cityEnableSpan) { cityEnableSpan.textContent = info.city_enabled ? '已启用' : '未启用'; } if (domainSpan) { domainSpan.textContent = info.domain_label || '未启用独立域名'; } statusSpan.textContent = info.message || ''; var previewUrl = info.preview_url_web || info.preview_url || info.preview_url_wap || info.fallback_url_web || info.fallback_url_wap || info.fallback_url; if (previewUrl && info.system_enabled && info.city_enabled) { var btn = document.createElement('a'); btn.href = 'javascript:void(0)'; btn.className = 'home-substation-btn pc-theme-button'; btn.textContent = '跳转到定位分站'; btn.onclick = function(){ if (info.flags && parseInt(info.flags.jump_confirm || 0, 10) === 1) { var confirmText = info.message ? info.message + '\n是否跳转到分站?' : '是否跳转到分站?'; if (!window.confirm(confirmText)) { return; } } window.location.href = previewUrl; }; btnHolder.appendChild(btn); } } else { statusSpan.textContent = message || '检测中…'; if (systemSpan) { systemSpan.textContent = '检测中…'; } if (cityEnableSpan) { cityEnableSpan.textContent = '检测中…'; } if (domainSpan) { domainSpan.textContent = '检测中…'; } } } // 显示城市选择器函数 window.showPcCitySelector = function(event) { if (event) { event.preventDefault(); event.stopPropagation(); } console.log('显示PC端城市选择器...'); // 检查是否已存在选择器 if (document.getElementById('pc-city-selector')) { return; } // 创建简单的城市选择弹窗 const modal = document.createElement('div'); modal.id = 'pc-city-selector'; modal.style.cssText = ` position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center; `; modal.innerHTML = `

选择城市

定位方式:检测中…
定位类型:检测中…
定位城市:检测中…
获取的IP:检测中…
系统分站:检测中…
城市分站:检测中…
域名模式:检测中…
检测中…

手动选择

搜索城市

`; document.body.appendChild(modal); // 确保DOM渲染完成后再更新(使用setTimeout确保DOM已渲染) setTimeout(function() { // 如果还没有定位信息,立即请求 if (!homeCurrentLocation || !homeCurrentLocation.city_id) { // 如果已经在定位中,不要重复调用 if (homeIPLocating) { console.log('弹窗打开:IP定位正在进行中,等待结果'); updateHomeLocationInfoFields(); applyHomeSubstationStatus(null, '检测中…'); return; } console.log('弹窗打开:没有定位信息,开始请求'); updateHomeLocationInfoFields(); // 先显示"检测中…" applyHomeSubstationStatus(null, '检测中…'); requestCityByIP(); return; } console.log('弹窗打开:已有定位信息', homeCurrentLocation); // 立即更新定位信息字段 updateHomeLocationInfoFields(); // 显示分站状态 if (homeSubstationStatusCache) { console.log('弹窗打开:使用缓存的分站状态'); applyHomeSubstationStatus(homeSubstationStatusCache); } else if (homeCurrentLocation.city_id > 0) { console.log('弹窗打开:请求分站状态'); homeSubstationStatusMessage = '检测中…'; applyHomeSubstationStatus(null, homeSubstationStatusMessage); fetchHomeSubstationStatus(homeCurrentLocation.city_id); } else { applyHomeSubstationStatus(null, '城市ID无效'); } }, 10); // 加载数据 loadPcSelectorData(); // 点击遮罩关闭 modal.addEventListener('click', function(e) { if (e.target === modal) { hidePcCitySelector(); } }); // 搜索框回车事件 document.getElementById('pc-city-search').addEventListener('keypress', function(e) { if (e.which === 13) { searchPcCities(); } }); }; // 加载PC端选择器数据 function loadPcSelectorData() { loadPcProvinces(); loadPcHotCities(); } function loadPcProvinces() { $.getJSON('/index.php?g=Home&m=LocationApi&a=getProvinceList', function(result){ if (result && result.success) { var select = $('#pc-province-select'); if (select.length) { var html = ''; $.each(result.data, function(_, province){ html += ''; }); select.html(html).off('change.pc').on('change.pc', function(){ loadPcCitiesByProvince(this.value); }); } } }); } function loadPcCitiesByProvince(provinceId) { var citySelect = $('#pc-city-select'); if (!provinceId) { citySelect.html(''); return; } $.getJSON('/index.php?g=Home&m=LocationApi&a=getCitiesByProvince&province_id=' + provinceId, function(result){ var html = ''; if (result && result.success) { $.each(result.data, function(_, city){ html += ''; }); } citySelect.html(html); }).fail(function(){ citySelect.html(''); }); } // 加载PC端热门城市 function loadPcHotCities() { $.getJSON('/index.php?g=Home&m=LocationApi&a=getCityList', function(result){ if (result && result.success) { var container = $('#pc-hot-cities'); if (container.length) { var html = ''; $.each(result.data.slice(0, 18), function(_, city){ html += '
' + city.city_name + '
'; }); container.html(html).off('click.hot').on('click.hot', '.pc-hot-city', function(){ selectPcCity($(this).data('id'), $(this).data('name')); }); } } }); } // 搜索PC端城市 function searchPcCities() { var keyword = $('#pc-city-search').val().trim(); var container = $('#pc-search-results'); var list = container.find('.pc-search-list'); if (!keyword) { list.empty(); container.hide(); return; } $.getJSON('/index.php?g=Home&m=LocationApi&a=searchCity&keyword=' + encodeURIComponent(keyword), function(result){ var html = ''; if (result && result.success && result.data && result.data.length) { $.each(result.data, function(_, city){ html += '
' + city.city_name + ' - ' + city.province_name + '
'; }); } else { html = '
未找到匹配的城市
'; } list.html(html).off('click.search').on('click.search', '.pc-search-item', function(){ selectPcCity($(this).data('id'), $(this).data('name')); }); container.show(); }); } // 选择PC端城市 function selectPcCity(cityId, cityName) { if (!cityId) return; $.post('/index.php?g=Home&m=LocationApi&a=setManualCity', { city_id: cityId }, function(result){ if (result && result.success && result.data) { updateCityDisplay(result.data, 'manual'); hidePcCitySelector(); alert('已切换到' + (result.data.city_name || cityName)); setTimeout(function(){ window.location.reload(); }, 800); } else { alert('城市切换失败:' + (result ? result.message : '未知错误')); } }, 'json').fail(function(){ alert('城市切换失败,请重试'); }); } function confirmPcCitySelection() { var citySelect = $('#pc-city-select'); if (!citySelect.length || !citySelect.val()) { alert('请选择城市'); return; } var cityName = citySelect.find('option:selected').text(); selectPcCity(citySelect.val(), cityName); } window.hidePcCitySelector = function() { $('#pc-city-selector').remove(); };
我要发布信息
  • 本地生活信息
copyright 2013-2113 www.chenshiwang.cn All Rights Reserved 陈氏家族网版权所有
皖ICP备2021016109号-1