如何将使用ajax上传的图像发送到php和其他参数

时间:2014-01-07 17:50:51

标签: javascript php jquery ajax

这是我的代码。我已经设法在浏览器中显示图像一旦上传但我不知道如何通过ajax解析该图像到php以便保存以供以后使用和额外的参数如id.Please help !!!

<input type="file" multiple="true" id="files" />
<input type="submit" id="go"/>
<div id="images"></div>
<script>
// set up variables
var reader = new FileReader(),
    i=0,
    numFiles = 0,
    imageFiles;

// use the FileReader to read image i
function readFile() {
    reader.readAsDataURL(imageFiles[i])
}

// define function to be run when the File
// reader has finished reading the file
reader.onloadend = function(e) {

    // make an image and append it to the div
    var image = $('<img>').attr('src', e.target.result);
    $(image).appendTo('#images');

    // if there are more files run the file reader again
    if (i < numFiles) {
        i++;
        readFile();
    }
};

$('#go').click(function() {

    imageFiles = document.getElementById('files').files
    // get the number of files
    numFiles = imageFiles.length;
    readFile();           

});



</script>

1 个答案:

答案 0 :(得分:0)

您可以在src标记中添加任何属性。发送到php时序列化这些属性并通过post或get发送。像这样:

<img src="" param-a="info-a" param-b="info-b" param-c="info-c" alt="">

<script type="text/javascript">
    jQuery(document).ready(function($) {
        var img = $("img");

        var myparams = new Array();
        myparams[0] = $(img).attr("param-a");
        myparams[1] = $(img).attr("param-b");
        myparams[2] = $(img).attr("param-c");

        var data = $.serializeArray(myparams);
    });
</script>

没有Jquery:

<img src="" id="img" param-a="info-a" param-b="info-b" param-c="info-c" alt="">

<script type="text/javascript">
var myparams = new Array();
myparams[0] = document.getElementById('img').getAttribute('param-a');
myparams[1] = document.getElementById('img').getAttribute('param-b');
myparams[2] = document.getElementById('img').getAttribute('param-c');

var data = JSON.stringify(myparams)

console.log(data);
</script>