0

我必须文件,在其中一个文件中,我使用 Javascript 调用另一个文件:

$(document).ready(function() {
  $('#dataBox').load('/example/data.php?id=' + '123');
});

然后数据很好地显示在我的 div 中,id 为“dataBox”。到目前为止,一切都很好。

不过,在我的 data.php 文件中,从数据库中查询的每个数据都有一个表单。简单的表单只是一个文本字段和一个提交按钮。此表单使用 POST 发送数据,然后第一个文件使用$_POST. 这不起作用,在我将获取数据的代码移动到另一个文件之前一切正常。表单操作参数设置为$_SERVER["REQUEST_URI"]。我可以与 Google Chrome 的开发人员一起检查东西,看到它将值发送到 data.php?id='123',这并不奇怪。所以我想我会将所有获取 POST 值的代码移到 data.php 文件中。虽然这似乎也不起作用。当我按下提交时,页面似乎没有刷新。

编辑:

我只是注意到我写<form ..some code .. /> instead of just <form ..some code .. >了这使得提交按钮“工作”并发送值。虽然它把我发送到 jQuery 加载页面,因为$_SERVER["REQUEST_URI"]它是 action 参数。我需要这样做,以便它将我发送到加载文件的页面。

4

3 回答 3

1

You need to reinitialize your jquery function when you load the new page. Jquery doesn't know it exists unless you reinit like so:

$(document).ready(function() {
  $('#dataBox').load('/example/data.php?id=' + '123', function(){
      reinit();
  });
});

function reinit() {
  $('#dataBox form').submit(function(){
    var formData = $(this).serialize();
    $.ajax({
        type: "POST",
        url: 'myProcessingPage.php',
        data: formData,
        success: function (data) {
            alert('success');
        },
        error: function (data) {
            alert('error');
        }
    });
  });
}

Note: This code is just to show you how it works, not meant for production.

于 2012-08-16T17:14:01.820 回答
0

一个 jQuery (1.7.2) 解决方案(这还不完整,您必须根据需要进行修改,我只是指出了另一种在不使用标准表单提交的情况下发布到 data.php 的替代方式):

$(document).ready(function() {
  // Like you already have, load the form stuff on document ready
  $('#dataBox').load('/example/data.php?id=' + '123');
  // Now, let's hook a submit event up to your submit buttons - we'll attach it to dataBox so 
  // you wont have to bind it again:
  $("#dataBox").delegate("submit","FORM",function(e){
     // Prevent the form from submitting
     e.preventDefault();
     // Do the submission
     $.post("data.php",{id:"123"},function(result){
        // Now you can do whatever you want with result, as it
        // contains everything that data.php returned.
     });
  });
});
于 2012-08-16T18:00:18.510 回答
0

啊……解决了!

只是改为$_SERVER["REQUEST_URI"]感谢$_SERVER["HTTP_REFERER"]您的所有帮助!让我了解出了什么问题,以及更多关于事情是如何运作的。:)

于 2012-08-16T18:31:44.763 回答