使用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');


});

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...