React表单提交至WordPress API后,PHP无法解析嵌套JSON数据问题
问题:React表单POST到WordPress admin-ajax后,PHP无法解析嵌套JSON
我搭建了集成React的WordPress站点,通过React表单向WP的admin-ajax.php发送POST请求,但PHP端无法正确解析嵌套的JSON数据。
前端请求代码
axios.post('/wp-admin/admin-ajax.php', new URLSearchParams({ action: 'report', report: JSON.stringify(props.data), nonce : document.getElementById("my-react-app").getAttribute("data_id") }), config) .then(response => console.log(response)) .catch((err) => { let message = typeof err.response !== "undefined" ? err.response.data.message : err.message; console.log("error", message); });
服务器接收的数据结构
服务器能收到请求,$_POST中的report字段是经过多重转义的JSON字符串,结构如下:
{"success":true,"data":{"action":"report","report":"{\\\"firstName\\\":\\\"rrt\\\",\\\"lastName\\\":\\\"trtr\\\",\\\"phone\\\":\\\"rt\\\",\\\"email\\\":\\\"rtrt\\\",\\\"placedata\\\":{\\\"Street\\\":\\\"tr\\\",\\\"City\\\":\\\"tr\\\",\\\"State\\\":\\\"tr\\\",\\\"zip\\\":\\\"tr\\\"},\\\"dateData\\\":{\\\"Start\\\":\\\"00:21\\\",\\\"End\\\":\\\"00:12\\\",\\\"Date\\\":\\\"2022-08-31\\\"},\\\"foodData\\\":{\\\"Food\\\":\\\"df\\\"},\\\"peopleData\\\":{\\\"People\\\":\\\"32\\\"}}","nonce":"f2331f42d4"}}
尝试的PHP代码(无效)
function report() { global $wpdb; $data = $_POST; $test_One = json_decode($data['report']->firstName; // 无输出,连Null都没有 $Test_two = json_decode($data['report']); // 输出原转义后的JSON字符串 echo "<xmp>"; // Test 3 print_r(json_decode($data['report'])['lastName']); // 只输出 "{" echo "</xmp>"; }
解决方案
问题核心是JSON字符串被双重转义:前端用JSON.stringify处理后,URLSearchParams发送时又自动转义了一次,导致PHP收到的是带\\\"的三重转义字符,json_decode无法正常解析。
方案1:前端优化(推荐)
直接发送JSON格式请求,避免URLSearchParams带来的额外转义,同时设置正确的请求头:
axios.post('/wp-admin/admin-ajax.php', { action: 'report', report: props.data, // 无需JSON.stringify,axios自动处理 nonce : document.getElementById("my-react-app").getAttribute("data_id") }, { headers: { 'Content-Type': 'application/json' } }) .then(response => console.log(response)) .catch((err) => { let message = typeof err.response !== "undefined" ? err.response.data.message : err.message; console.log("error", message); });
对应PHP处理代码:
function report() { global $wpdb; // 读取原始JSON请求体 $raw_data = file_get_contents('php://input'); $request = json_decode($raw_data, true); // 验证nonce(替换为你的nonce动作名) if (!wp_verify_nonce($request['nonce'], 'your_nonce_action')) { wp_send_json_error('无效的nonce'); } // 直接访问解析后的嵌套字段 $firstName = $request['report']['firstName']; $street = $request['report']['placedata']['Street']; // 业务逻辑处理... wp_send_json_success(['firstName' => $firstName]); }
方案2:仅修复PHP端(不修改前端)
对收到的report字符串先反转义,再解析JSON:
function report() { global $wpdb; $data = $_POST; // 去掉多余的转义符,恢复正常JSON格式 $clean_report = stripslashes($data['report']); // 解析为关联数组(第二个参数true),方便直接访问字段 $report_data = json_decode($clean_report, true); // 现在可以直接获取嵌套数据 $firstName = $report_data['firstName']; $lastName = $report_data['lastName']; $endTime = $report_data['dateData']['End']; print_r($report_data); // 查看完整解析结果 }
关键说明
URLSearchParams会自动转义特殊字符,导致JSON.stringify后的字符串被二次转义,产生\\\"这类无效转义符。stripslashes()可以移除这些多余的转义,让json_decode正确识别JSON结构。- 直接发送JSON请求更符合现代API规范,能从根源避免转义问题。
内容的提问来源于stack exchange,提问作者Swalt
相关产品推荐
相关产品推荐

