2014-10-07 26 views
0

我使用一個使用canvas元素將圖像編碼爲base64的函數對圖像進行編碼。
後來我嘗試通過AJAX中的Base64字符串張貼到我的PHP ajax_controllerVanilla JS Ajax和base64img問題

function submitParticipation(name,email,phone,city) { 
    encodeImage(uploadedImg, function(encodedImage) { 
     uploadedImg = encodedImage; 
    }); 

    var ajax = new XMLHttpRequest(); 
    var params = 'uid='+ facebookUserId + '&name=' + name + '&email=' + email + 
     '&phone=' + phone + '&city=' + city + '&img_string=' + base64Img + 
     '&facebook_name=' + facebookUserFullName + '&facebook_pic=' + 
     facebookProfilePic + '&facebook_email=' + facebookUserEmail; 

    ajax.open("POST", "main_ajax_controller.php?m=store_participation", true); 
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    ajax.send(params); 
    ajax.onreadystatechange = function() { 
     if (ajax.readyState == 4 && ajax.status == 200) { 
      var response = ajax.responseText; 
     }   //If an error occur during the ajax call. 
     if (ajax.readyState == 4 && ajax.status == 404) { 

     } 
    } 
} 

base64Img雖然不通過AJAX調用 - 它通過空。

任何想法爲什麼?

base64Img變量被定義得很好 - 我可以看到這一點,因爲我在將它記錄在控制檯中之前,在定義Ajax調用的params變量之前。

回答

1

您的參數字符串無效,因爲您不編碼每個值。所有這些,包括base64值都應該包含在encodeURIComponent()中。

例如:

base64Img = encodeURIComponent(base64Img); 

Base64的值包括=字符,其被打破了密鑰對字符串。

+0

爲什麼其餘的params需要這個,如果它只是base64'='這是打破這個? – 2014-10-07 10:00:02

+0

爲了符合'application/x-www-form-urlencoded'標準格式,需要對其他特殊字符(不只是'='和'&')進行編碼。即使你相信在這些值中不會有特殊字符,反正仍然是很好的編碼方式。 – MrCode 2014-10-07 10:02:07

+0

明白了,謝謝! – 2014-10-07 10:04:36