使用jQuery Ajax跳转至PHP页面失败问题求助
问题解决:点击Properties按钮Ajax不跳转页面
核心问题分析
- Ajax参数格式错误:你的
data参数写法完全不符合jQuery要求,不能直接罗列变量,必须是键值对对象或URL编码字符串,否则服务器无法正确接收参数。 - Ajax本身不触发页面跳转:Ajax是异步请求,只会和服务器交互数据,不会主动让浏览器跳转到新页面,需要手动实现跳转逻辑。
- (可选)动态按钮绑定的潜在问题:多次点击Save按钮会重复生成Properties按钮,每次都会绑定新的点击事件,可能引发重复请求。
修正方案
方案一:修复Ajax请求+手动跳转(适合需要先获取服务器响应再跳转的场景)
修改scripts.js中的Ajax部分,修正参数格式并添加跳转逻辑:
$(function() { $('#btn').click(function() { let inp1 = $('#inp1').val(); let inp2 = $('#inp2').val(); let div1 = $('#div1'); let div2 = $('#div2'); let div3 = $('#div3'); div1.html(inp1) div2.html(inp2); if(inp1 && inp2) { let btn = $('<button>Properties</button>'); div3.html(btn); btn.click(function() { console.log('hello') $.ajax({ url: 'new.php', method: 'post', // 修正data为键值对对象 data: { input1: inp1, input2: inp2, action: 'prop' }, // 请求成功后手动跳转 success: function(response) { // 如果需要携带参数跳转,用GET方式 window.location.href = `new.php?input1=${encodeURIComponent(inp1)}&input2=${encodeURIComponent(inp2)}&action=prop`; // 若必须用POST跳转,参考方案二 }, // 捕获错误便于调试 error: function(xhr, status, err) { console.error('请求失败:', err); } }) }) } }) })
方案二:直接用动态表单提交(适合仅需提交参数并跳转的场景,无需Ajax)
如果你的需求只是提交参数并跳转到new.php,完全不需要Ajax,动态创建表单提交更简单:
$(function() { $('#btn').click(function() { let inp1 = $('#inp1').val(); let inp2 = $('#inp2').val(); let div1 = $('#div1'); let div2 = $('#div2'); let div3 = $('#div3'); div1.html(inp1) div2.html(inp2); if(inp1 && inp2) { let btn = $('<button>Properties</button>'); div3.html(btn); btn.click(function() { console.log('hello') // 动态创建POST表单 const form = $('<form>', { method: 'POST', action: 'new.php' }); // 添加隐藏参数 form.append($('<input>', {type: 'hidden', name: 'input1', value: inp1})); form.append($('<input>', {type: 'hidden', name: 'input2', value: inp2})); form.append($('<input>', {type: 'hidden', name: 'action', value: 'prop'})); // 提交表单触发跳转 form.appendTo('body').submit(); }) } }) })
可选优化:事件委托绑定动态按钮
如果多次点击Save按钮,每次都会生成新的Properties按钮,建议用事件委托绑定点击事件,避免重复绑定:
// 把按钮绑定逻辑替换为事件委托 $(function() { $('#btn').click(function() { // ... 原有逻辑不变 ... if(inp1 && inp2) { div3.html('<button>Properties</button>'); } }) // 事件委托:监听div3内的按钮点击 $('#div3').on('click', 'button', function() { let inp1 = $('#inp1').val(); let inp2 = $('#inp2').val(); console.log('hello') // 这里写Ajax或表单提交逻辑 }) })
内容的提问来源于stack exchange,提问作者Andrey
相关产品推荐
相关产品推荐

