1

I am getting an array returned from PHP which I json_encode() in php first and I echo that array. I get the array with an AJAX request disabling "Async". I know I shouldn't use that but it was the only way I could find.

It returns me this:

{"id":"38","name":"111111111111111111111111111111111111111111111.jpg"}

And this is my AJAX request:

function uploadFile(file){
    var formData = new FormData();
    formData.append('formData', file);
    $.ajax({
        url: 'inc/ajax/uploadFile.php',  //Server script to process data
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        async:   false,
        //Ajax events
        success: function(html){
            strReturn = html;
        }
    });
    return strReturn;
}

When I do this I get the whole array:

var img = uploadFile(file);
console.log(img);

But when I call "img.name" or img.id" it says undefined.

4

3 回答 3

3

您将收到一个对象的 JSON 字符串表示。告诉 jQuery 你期待 JSON,以便它为你将其解析为一个实际的 Javascript 对象:

data: formData,
dataType: 'json', // Add this line
于 2013-08-28T19:19:30.920 回答
1

您需要将 dataType 设置为 json ,并且您应该使用可能strReturn在填充之前返回的回调。

function uploadFile(file,callback){
    var formData = new FormData();
    formData.append('formData', file);
    $.ajax({
        url: 'inc/ajax/uploadFile.php',  //Server script to process data
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        dataType: "json",
        //Ajax events
        success: function(html){
            strReturn = html;
            callback(strReturn);
        }
    });
}

uploadFile(file,function(img){
    console.log(img.name);
});
于 2013-08-28T19:23:54.687 回答
0

尝试这个:

function uploadFile(file){
    var formData = new FormData();
    formData.append('formData', file);
    $.ajax({
        url: 'inc/ajax/uploadFile.php',  //Server script to process data
        type: 'POST',
        data: formData,
        contentType: false,
        dataType: "json",
        processData: false,
        //Ajax events
        success: function(html){
            strReturn = html;
            return strReturn;
        }
    });
}

它说未定义,因为在您返回它时未定义 strReturn。ajax 的成功方法会延迟几毫秒调用,因此您必须在 ajax 完成后返回您的变量。

于 2013-08-28T19:21:40.870 回答