微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Ajax将图像传递给PHP

我试图将图像和标题字段值传递给PHP,我通常使用$_FILES数组直接使用PHP处理文件上传,我不知道如何使用ajax创建/传递此数组到PHP.
我的表格:

<form role="form" name="updateProductForm" id="updateProductForm" method="POST" enctype="multipart/form-data"> 
    <input name="imgOne" id="imgOne" type="file" title="Add Image">
    <a class="btn btn-primary" name="updateProduct" id="updateProduct">Update Product</a></div>
</form>

我试图用它来传递给PHP

$('#updateProduct').on('click', function() {
    try {
        ajaxRequest = new XMLHttpRequest();
    } catch (e) {
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("Your browser broke!");
                return false;
            }
        }   
    }
    ajaxRequest.open("POST", "../Controller/ProductController.PHP", true);
    ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    ajaxRequest.send("title=" + $("#title").val() + "&imgOne=" + $("#imgOne"));

    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            console.log(ajaxRequest);
        }
    }

});

PHP中我试试这个:

if (isset($_POST["edit"])) {
    $id = $_POST["edit"];
    $imgName = $_FILES["file"]["imgName"];
}

优素福

解决方法:

我在我的一个项目中做到了这一点,以下代码为我工作.
请根据需要对代码进行必要的修改.

我的表格按钮:

 <form name="upload_img" enctype="multipart/form-data" id="upload_img">
<input type="file" style="display:none" id="upload-image" name="upload-image"></input>
<button id="upload_image" type="button">Save</button>
</form>

我的JQuery / Ajax:

$('#upload_image').click(function()
{
    var form = new FormData(document.getElementById('upload_img'));
    //append files
    var file = document.getElementById('upload-image').files[0];
    if (file) {   
        form.append('upload-image', file);
    }
    $.ajax({
        type: "POST",
        url: "URL",
        data: form,             
        cache: false,
        contentType: false, //must, tell jQuery not to process the data
        processData: false,
        //data: $("#upload_img").serialize(),
        success: function(data)
        {
            if(data == 1)
                $('#img_msg').html("Image Uploaded Successfully");
            else
                $('#img_msg').html("Error While Image Uploading");
        }
    });
    //alert('names');


});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐