【问题标题】:require_once() or AJAX causing php script to run twicerequire_once() 或 AJAX 导致 php 脚本运行两次
【发布时间】:2017-04-11 14:16:42
【问题描述】:

我正在制作一个分步表单,在您按照步骤操作时存储会话变量。

在一个步骤中,我有一个文件上传,它可以预览图像并显示一个上传按钮,按下该按钮时会调用一个需要修改 $_SESSION 变量的 php 脚本,并回显上传文件的路径。

当我在没有require_once('config.php') 的情况下在调试器中对其进行测试时,它完全按照我的预期工作,显示图像及其文件名,但是,由于某种原因,当我包含配置文件时,当我在调试器中迭代它时,它似乎运行了两次 php 脚本,它正确更新了会话变量,但文件名不再回显,并且数据在到达前端之前丢失了。

我不知道错误是在 config.php 文件中,还是在 AJAX 调用中,或者可能是我丢失的其他地方。

标记('step4.php'):

<form method="post" action="step5.php">
    <span id="newfile">
        <input type="file" name="uploaded_file" id="imageupload" accept=".jpg, .jpeg, .png">
        <img alt="Preview Loading..." id="imagepreview">
    </span>
    <!-- The submit button is elsewhere before the end of the form, it acts as a next button -->
</form>

javascript函数:

$(document).on('click', '#uploadbutton', function(e) {
    e.preventDefault();
    //Grab upload elements and and file
    var uploadbutton = this;
    var uploader = document.getElementById('imageupload');
    var file = document.getElementById('imageupload').files[0];
    //Hide the upload elements
    uploadbutton.parentNode.removeChild(uploadbutton);
    uploader.parentNode.removeChild(uploader);
    //Make the form and pass it to server
    var formData = new FormData();
    formData.append('file', file); //$_FILES['file']
    $.ajax({
        url: 'uploadfile.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false
    })
    .done(function(data) {//Data is the relative path to the file
        //Hide the old content
        document.getElementById('newfile').innerHTML = '';
        //Show the new image
        var text = document.createTextNode('Uploaded File: '+data.replace('temp/', '', data));
        var br = document.createElement("br");
        var imgElement = document.createElement("IMG");
        imgElement.setAttribute('src', data);
        document.getElementById('newfile').appendChild(text);
        document.getElementById('newfile').appendChild(br);
        document.getElementById('newfile').appendChild(imgElement);
    })
    .fail(function() {
        alert("Error uploading the file. Hit refresh and try again.");
    });
});

'uploadfile.php':(我的调试器显示的那个被执行了两次......)

<?php
//require_once('config.php'); //THE PROBLEM?

if($_FILES) {
    //Get the uploaded file information
    $name_of_uploaded_file = $_FILES['file']['name'];
    //Actually upload the file to the server!
    $upload_folder = 'temp/'; //Make a file named temp
    $path_of_uploaded_file = $upload_folder.$name_of_uploaded_file;
    $tmp_path = $_FILES["file"]["tmp_name"];

    if(is_uploaded_file($tmp_path)) {
        copy($tmp_path,$path_of_uploaded_file);
        $_SESSION['step4filepath'] = $path_of_uploaded_file;
        echo $path_of_uploaded_file;
    }   
}

?>

'config.php':包含在内时会搞砸的东西

<?php
session_start();

//Initialize session data
if(empty($_SESSION)) {
    if(!isset($_SESSION['step4filepath'])) {
        $_SESSION['step4filepath'] = '';
    }
}

//Update session data
if($_SERVER['REQUEST_METHOD'] === 'POST') {

    if($_SESSION['currentPage'] == 4) {
        //input for step 4, we just want filename if they submit the form
        $_SESSION['step4filepath'] = $_POST['step4filepath'];
    }
    //Enable us to hit the back button!
    header("Location: " . $_SERVER['REQUEST_URI']);
}
?>

完全迷失了这一点。

【问题讨论】:

    标签: javascript php jquery ajax session


    【解决方案1】:

    可能是这个?为什么你的配置文件中有那行?

    header("Location: " . $_SERVER['REQUEST_URI']);
    

    【讨论】:

    • 似乎有效!我是这样设置的,这样您就可以在浏览器中使用后退按钮,而不会偶尔出现Confirm Form Resubmission 消息。当用户当前在第 4 页时,我拒绝了它。(你回答得太快了,我不得不稍等片刻才能将你标记为回答它的人。)谢谢!
    • 不要像这样添加回功能......使用history.back(),如果你想用PHP来做,那么试着在你的代码中添加更多的条件。如果按钮点击值是这个,那么只有返回等。
    • 您建议什么条件?发布的是非敏感信息。
    • 我不确定您打算如何启用/使用它作为后台功能。 1. 在你的后退/取消按钮上使用它... 2. 你也可以使用 window.history.back()
    【解决方案2】:

    看起来 config.php 正在用 $_POST['step4filepath'] 替换 $_SESSION['step4filepath'] 的值,而不是将其保留为 $path_of_uploaded_file。

    编辑

    正如在别处提到的, header() 将导致重新加载。我的回答无关紧要,因为在设置 var 之前调用了 config.php。

    【讨论】:

      【解决方案3】:

      解决方案 1

      替换

      $(document).on('click', '#uploadbutton', function(e) { 
      

      $(document).off('click').on('click', '#uploadbutton', function(e) {
      

      解决方案 2:参见下面的示例代码

      $(document).on("click", "#someID", function(e) {
          $(this).attr("disabled","disabled");
          // Disabling the input stops the event from firing multiple times.
          var targetObj = $(this);
          // targetObj can be used within the $.POST function, not $(this)
         var myVariable = "Hello world";
         $.post("/DoSomethingAJAXY.php", { variable1: myVariable },
         function(data, status){
          if (status == "success") {
              // Do something
          }
          $(targetObj).removeAttr("disabled");
          // Re-enable the event input trigger
      });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-14
        • 1970-01-01
        • 1970-01-01
        • 2014-02-05
        • 2017-10-13
        • 2013-07-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多