<button id="btnSubmit">提交圖片路徑</button>
<script>
document.getElementById('btnSubmit').addEventListener('click', async () => {
// 1. 獲取所有 class="c1" 的圖片 src
const images = document.getElementsByClassName('c1');
const srcArray = Array.from(images).map(img => img.src);
// 2. 用 JSON 發送(推薦),或用 '_' 連接字符串
const payload = { imageUrls: srcArray }; // 結構化數據,後端易解析
try {
const res = await fetch('1.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const result = await res.json();
console.log('後端響應:', result);
alert('提交成功');
} catch (err) {
console.error('提交失敗:', err);
alert('網絡錯誤');
}
});
</script>
<?php
header('Content-Type: application/json');
// 讀取原始 JSON 流
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_encode(['code' => 400, 'msg' => 'JSON 解析失敗']);
exit;
}
$imageUrls = $data['imageUrls'] ?? [];
if (empty($imageUrls)) {
echo json_encode(['code' => 200, 'msg' => '無圖片數據']);
exit;
}
// 業務邏輯:入庫、下載、記錄日志...
// 示例:寫入文件
file_put_contents('image_log.txt', date('Y-m-d H:i:s') . ' ' . implode(',', $imageUrls) . PHP_EOL, FILE_APPEND);
echo json_encode(['code' => 200, 'msg' => '接收成功', 'count' => count($imageUrls)]);
?>
$_POST 只能解析 application/x-www-form-urlencoded 或 multipart/form-data,不支持 JSON。header('Access-Control-Allow-Origin: *');。$('#btnSubmit').click(function() {
var srcArray = $('.c1').map(function() { return this.src; }).get();
$.ajax({
url: '1.php',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ imageUrls: srcArray }),
dataType: 'json',
success: function(res) { console.log(res); }
});
});
現代項目建議直接用 fetch 或 axios,輕量且標準化。