javascript - 为什么在 Post 过程中 JQuery 会加载到 PHP 页面中?

标签 javascript php jquery html mysql

您好,我一直在开发一个可以提交图像的网站。我不希望提交图片时重新加载页面。图片发布到 php 页面后,它会以 BLOB 形式存储在 MYSQL 数据库中。

            form id="form2" action="saveImage.php" method="post" enctype="multipart/form-data">
            <input id="thumbage2" name="Image1" class="ModalArea2" type="file" style="display:none">       
            <center><label for="thumbage2" id="labelthumb2" style="margin-top:35px;">Choose Image</label></center>

            <button class="ModalButton2" >Submit</button>
            <a class="ModalButton2" onclick="cancel2();">Cancel</a>
            </form>

上面是我的 HTML 代码。这是我的 javascript/jQuery 代码:

     $(':file').change(function(){
    var file = this.files[0];
    var name = file.name;
    var size = file.size;
    var type = file.type;
    //Your validation
    //console.log(name);
});

$(':button').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'upload.php',  //Server script to process data
        type: 'POST',
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // Check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: beforeSendHandler,
        success: completeHandler,
        error: errorHandler,
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
    cancel2();
});

我从网站复制了这段代码,但他们没有很好地解释它是如何工作的。所以目前我已将数据发布到我的 PHP 文件中并且它可以工作。问题是 PHP 文件已加载。我认为 JQuery 的重点不是加载文件而是停留在同一页面上。为什么这不会发生?为什么我的浏览器中不断加载 PHP 页面?谢谢,如果你帮我解决这个问题,我会欣喜若狂,最近对我来说真是一个巨大的打击。

最佳答案

我曾经遇到过类似的问题,据我搜索,上传文件而不重新加载页面的唯一方法是使用 iFrames。但对我来说,iFrame 很丑陋。

下面的方法将图像转换为数据 URL,而不是上传图像,而是将数据 URL(只是一个字符串)上传到服务器。

我对您的 HTML 代码进行了一些更改。我们不想提交表单,因为这会导致网页在浏览器中重新加载。添加onsubmit = 'return false;'添加到表单标记将阻止单击提交按钮时提交表单。

我向输入元素添加了一些 ID,以便在 JQuery 中访问时使它们具有唯一性。

然后我添加了一个带有 src 的图像元素属性。当用户从输入框中选择图像时,src该元素的属性被图像的数据 URL 填充。

<form id="form2" action="saveImage.php" onsubmit="return false;" method="post" enctype="multipart/form-data">
    <input id="imageSelect" name="Image1" class="ModalArea2" type="file" style="display:block;">       
    <center><label for="thumbage2" id="labelthumb2" style="margin-top:35px;">Choose Image</label></center>
    <button class="ModalButton2" id="uploadImageButton">Submit</button>
    <a class="ModalButton2" onclick="cancel2();">Cancel</a>
    <img id="imgURL" src="none"/>
</form>

接下来是您的 JavaScript 代码。这些评论将帮助您了解它是如何工作的。主要变化是

向输入按钮添加了一个事件处理程序以选择图像。当用户使用输入按钮选择图像时,将触发 onchange 事件并显示 <img>元素的src属性填充图像的数据 URL。

第二个主要更改是 AJAX 请求。我已将其更改为 .post ,因为它更容易阅读(至少对我来说)并且在该请求中,我们不是发送图像本身,而是发送从 <img> 抓取的图像的数据 URL。标签的src属性。该数据以 JSON 格式发送,因此处理上传请求的 PHP 脚本应读取 JSON 格式的数据。

$(':file').change(function(){
    var file = this.files[0];
    var name = file.name;
    var size = file.size;
    var type = file.type;
    //Your validation
    //console.log(name);
});

$('#uploadImageButton').click(function(){
    var imgData = $('#imgURL').src;
    $.post({
        'upload.php', // Name of the PHP script which handles upload function
        {imageData:imgData}, // Use $_POST['imageData] to access the image data in your PHP script
        function data() {
            // whatever you want to do after the POST request is complete
            alert('Uploaded image');
        };

    });
});

$('#imageSelect').change(function(){
    readURL(this);
});

function readURL(input)
{
    if(input.files && input.files[0])
    {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#imgURL').attr('src', e.target.result);
        };
    }
    reader.readAsDataURL(input.files[0]);
}

您需要编辑 PHP 脚本,以便它以 JSON 格式读取图像的数据 URL,然后将数据 URL 保存为图像文件。它应该看起来像这样:

<?php
    function upload()
    {
        if(isset($_POST))
        {
            // Get the image data URL
            $imageData = $_POST['imageData'];

            // Replace the spaces with plus signs
            $imageData = str_replace(' ', '+', $imageData);

            // Decode the image data
            $imageData = base64_decode($imageData);

            // Path where you want to save the image
            $uri = "/image.png";

            // Save the image data to an image file on the server
            file_put_contents($imageData, $uri);

        }
    }
?>

关于javascript - 为什么在 Post 过程中 JQuery 会加载到 PHP 页面中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40831502/

相关文章:

php - 延迟显示多个 Noty 通知

php - 加载页面时 session 的未定义索引错误

jquery - 垂直图像调整

javascript - Select2 更改事件 - 在第一个 select2 框值更改时更改下一个 select2 框的选项

javascript - 如何使用 jQuery 获取在 HTML 页面中创建的所有跨度

javascript - CheckboxInputElement.onChange 事件未触发

javascript - Canvas 内存使用总量超出最大限制 (Safari 12)

javascript - 在日 View 中的全天上方添加自定义标题

php - 验证字符串是否以给定的子字符串开头

javascript - jQuery 在单击元素外部时隐藏元素按预期工作,但实际上并非如此