HTML 示例代码 <label for="siteurl">输入网址:</label> <input type="text" id="siteurl" name="siteurl" oninput="checkSiteUrl()"> <span id="result"></span>
<script> function checkSiteUrl() { const siteurl = document.getElementById('siteurl').value; if (siteurl.trim() === '') return;
// 发送 AJAX 请求到后端 fetch('/check-url', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ siteurl }) }) .then(response => response.json()) .then(data => { const resultElement = document.getElementById('result'); if (data.exists) { resultElement.style.color = 'red'; resultElement.textContent = '此网址已存在!'; } else { resultElement.style.color = 'green'; resultElement.textContent = '此网址可用。'; } }) .catch(error => console.error('Error:', error)); } </script>
后端PHP
<?php header('Content-Type: application/json');
// 假设这是数据库中的已有 URL 列表 $existing_urls = [ "http://www.qq.com/", "https://qq.com", "http://example.com" ];
// 获取前端传来的数据 $input_url = $_POST['siteurl'] ?? '';
if (empty($input_url)) { echo json_encode(['exists' => false]); exit; }
/** * 对 URL 进行标准化处理 */ function normalize_url($url) { // 解析 URL $parsed_url = parse_url($url);
// 提取域名部分 $host = strtolower($parsed_url['host'] ?? ''); if (substr($host, 0, 4) === 'www.') { $host = substr($host, 4); // 去掉 www. }
// 提取路径部分并去掉多余的斜杠 $path = isset($parsed_url['path']) ? rtrim($parsed_url['path'], '/') : '';
// 返回标准化后的 URL return [ 'host' => $host, 'path' => $path ]; }
/** * 生成所有可能的 URL 变体 */ function generate_variations($normalized_url) { $variations = []; $protocols = ['http', 'https']; $host = $normalized_url['host']; $path = $normalized_url['path'];
foreach ($protocols as $protocol) { // 不带 www. $variations[] = $protocol . '://' . $host . $path;
// 带 www. $variations[] = $protocol . '://www.' . $host . $path; }
return $variations; }
// 标准化输入的 URL $normalized_input = normalize_url($input_url);
// 生成所有可能的变体 $variations = generate_variations($normalized_input);
// 检查变体是否存在于数据库中 $exists = false; foreach ($variations as $variation) { if (in_array($variation, $existing_urls)) { $exists = true; break; } }
// 返回结果 echo json_encode(['exists' => $exists]); ?>
|