Jet Engine表单Webhook端点实现用户页面重定向方法咨询
解决Jet Engine表单提交后通过REST端点动态重定向的问题
问题根源
Jet Engine表单默认通过Ajax提交数据,自定义REST端点返回的重定向指令只会发送给发起请求的JavaScript客户端,不会直接触发浏览器跳转。同时Jet Engine自带的重定向动作无法根据Webhook执行结果动态切换目标页面,因此需要前端配合处理跳转逻辑。
解决方案
1. 修正后端REST端点代码
先移除#[NoReturn]注解(函数实际返回了WP_REST_Response,该注解会导致PHP语法错误),确保返回的JSON数据包含redirect字段:
function endpoint_register_reservation( WP_REST_Request $request ): WP_REST_Response { $event_id = $request->get_param( 'event_id' ); $child_id = $request->get_param( 'child_id' ); $bookings = new reservations_manager(); $error = $bookings->create_reservation( $child_id, $event_id, false, false ); $booking_request_success = 'https://[redacted]/buchungswunsch-erhalten/'; $booking_request_failed = 'https://[redacted]/buchungswunsch-nicht-akzeptiert/'; if ( is_wp_error( $error ) ) { $booking_request_failed = add_query_arg( 'error_code', $error->get_error_code(), $booking_request_failed ); return new WP_REST_Response( array( 'redirect' => $booking_request_failed ), 200 ); } return new WP_REST_Response( array( 'redirect' => $booking_request_success ), 200 ); }
2. 添加前端JavaScript处理跳转
在主题functions.php中添加以下代码,或通过自定义JS插件/代码片段工具添加,监听Jet Engine表单的提交成功事件,获取后端返回的redirect URL并触发浏览器跳转:
add_action( 'wp_footer', 'jet_form_redirect_after_submit' ); function jet_form_redirect_after_submit() { // 替换为你的Jet Engine表单ID,留空则监听所有表单 $form_id = 'YOUR_FORM_ID'; ?> <script> document.addEventListener('DOMContentLoaded', function() { // 监听Jet Engine表单提交成功事件 document.addEventListener('jetEngineForms.submitSuccess', function(event) { const formData = event.detail; if (formData.response && formData.response.redirect) { // 触发浏览器跳转 window.location.href = formData.response.redirect; } }); }); </script> <?php }
如果上述事件无法捕获,可改用全局Ajax完成事件监听,判断请求URL是否匹配你的REST端点:
add_action( 'wp_footer', 'jet_form_redirect_after_submit' ); function jet_form_redirect_after_submit() { // 替换为你的REST端点URL路径,例如 '/wp-json/custom/v1/reservation' $endpoint_path = '/wp-json/your-namespace/v1/reservation'; ?> <script> document.addEventListener('DOMContentLoaded', function() { jQuery(document).ajaxComplete(function(event, xhr, settings) { if (settings.url.includes('<?php echo esc_js($endpoint_path); ?>')) { try { const response = JSON.parse(xhr.responseText); if (response.redirect) { window.location.href = response.redirect; } } catch (e) { console.error('解析重定向响应失败:', e); } } }); }); </script> <?php }
逻辑说明
- 后端REST端点处理预订逻辑后,返回包含跳转URL的JSON响应
- 前端通过监听Jet Engine表单提交事件或Ajax完成事件,提取跳转URL
- 调用
window.location.href强制浏览器跳转到目标页面,实现动态重定向需求
内容的提问来源于stack exchange,提问作者Milan Dierick
相关产品推荐
相关产品推荐

