如何在post数据中进行ajax调用-->图像和自定义数据(名称和值对)


How to make ajax call in post data --> image & custom data(name and value pair)

>我正在创建一个应用程序来上传图像及其路径,并且每个图像都有单独的路径

data:  {name:"niks",age:"22",path:"small/data",image:new FormData(this)}

我也想接收PHP代码中的数据和图像。

逻辑上我已经写了这段代码,什么是正确的代码请帮帮我。

HTML 表单代码是

<form id="replaceimg" enctype="multipart/form-data" method="post">
<input name="fileimg" type="file" id="fileimg"  required />
<input type="submit" value="Upload Image" name="submit" />
</form>

我的代码是:

$("#replaceimg").on('submit',(function(e) {
    e.preventDefault();
    $.ajax({
        url: "upload.php",      // Url to which the request is send
        type: "POST",                   // Type of request to be send, called as method
        data:  {name:"niks",age:"22",path:"small/data",image:new FormData(this)},       // Data sent to server, a set of key/value pairs representing form fields and values
        contentType: false,             // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
        cache: false,                   // To unable request pages to be cached
        processData:false,              // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
        success: function(data)         // A function to be called if request succeeds
        {
            console.log("data is "+data);
        }
    });
    alert("In Submit replaceimg");
}));

您必须将 FormData 对象作为数据参数传递。 jQuery AJAX 'multipart/form-data' 不发送数据?

但是,或者,如果图像不是那么大,您可以上传base64字符串。

试试这个:

var uploadFile = $('.nameOfInputClass') // <- Change the class.
var data = {};
data.name = 'Niks';
data.age = 22; // Should be a Number, not a string.
data.path = 'small/data';
data.image = new FormData();
data['image'].append('upload', uploadFile[0]);

他们:

$("#replaceimg").on('submit',(function(e) {
    e.preventDefault();
    $.ajax({
        url: "upload.php",      // Url to which the request is send
        type: "POST",                   // Type of request to be send, called as method
        data:  data,
        contentType: false,             // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
        cache: false,                   // To unable request pages to be cached
        processData:false,              // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
        success: function(data)         // A function to be called if request succeeds
        {
            console.log("data is "+data);
        }
    });
    alert("In Submit replaceimg");
}));