AJAX+SERIALIZE提交表单,PHP写入JSON文件无响应问题求助
问题排查与修复方案
先看最致命的问题——你的PHP代码里有个语法错误,直接导致脚本无法正常运行:
在获取表单的wallet-name字段时,你写了:
'walletname'=> $_POST['"wallet-name'],
这里的键名里多了一个多余的双引号,正确的写法应该是:
'walletname'=> $_POST['wallet-name'],
这个语法错误会让PHP脚本直接中断,没有任何输出返回给AJAX请求,所以你看不到success或error的回调触发。
接下来,我们再梳理其他可能存在的隐患,以及对应的修复:
1. 增加JSON解码的错误检查
如果原JSON文件格式有误,json_decode会返回null,后续的count($arr_data)会引发错误。可以添加检查:
$arr_data = json_decode($jsondata, true); if ($arr_data === null) { throw new Exception("Failed to decode JSON file: " . json_last_error_msg()); }
2. 确保文件写入权限
file_put_contents失败的常见原因是js/data.json文件或js目录没有写入权限。你可以手动设置文件权限为644,目录权限为755,或者在PHP里先检查是否可写:
if (!is_writable($myFile)) { throw new Exception("File is not writable: " . $myFile); }
3. AJAX调试优化
当前的AJAX代码没有打印实际的响应内容,很难排查问题。可以修改回调函数,查看具体的响应和状态:
var a = $('#add-wallet-form').serialize(); $.ajax({ type: 'POST', url: 'save.php', data: a, beforeSend: function() { console.log('Form data:', a); // 用console.log代替alert,更清晰 }, success: function(response) { console.log('Success response:', response); myApp.alert('OK'); }, error: function(xhr, status, error) { console.log('Error details:', status, error); console.log('Response:', xhr.responseText); myApp.alert('Not OK'); } });
同时,打开浏览器的开发者工具-网络面板,查看请求的状态码(比如500代表服务器错误)和响应内容,这是排查AJAX问题的关键。
修正后的完整PHP代码
<?php $myFile = "js/data.json"; $arr_data = array(); try { // 检查文件是否存在 if (!file_exists($myFile)) { throw new Exception("JSON file not found: " . $myFile); } // Get data from existing json file $jsondata = file_get_contents($myFile); if ($jsondata === false) { throw new Exception("Failed to read JSON file"); } // converts json data into array $arr_data = json_decode($jsondata, true); if ($arr_data === null) { throw new Exception("Failed to decode JSON: " . json_last_error_msg()); } $id = count($arr_data) + 1; $icon = "generic-wallet.png"; $amount = "12,000"; // 检查表单字段是否存在 if (!isset($_POST['wallet-name'], $_POST['wallet-select-bank'], $_POST['wallet-select-currency'])) { throw new Exception("Missing required form fields"); } // Get form data $formdata = array( 'id' => $id, 'walletname' => $_POST['wallet-name'], 'bank' => $_POST['wallet-select-bank'], 'icon' => $icon, 'currency' => $_POST['wallet-select-currency'], 'amount' => $amount ); // Push user data to array array_push($arr_data, $formdata); // Convert updated array to JSON $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT); if ($jsondata === false) { throw new Exception("Failed to encode JSON: " . json_last_error_msg()); } // 检查文件是否可写 if (!is_writable($myFile)) { throw new Exception("File is not writable: " . $myFile); } // write json data into data.json file if (file_put_contents($myFile, $jsondata)) { echo "ok"; } else { throw new Exception("Failed to write to JSON file"); } } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; // 可以设置HTTP状态码为500,让AJAX触发error回调 http_response_code(500); } ?>
按照上面的步骤修复后,应该就能正常写入JSON文件了。记得先检查网络面板的请求状态,这能帮你快速定位剩余问题。
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

