我有一個PHP腳本,用於計算時間序列數據中的下一個值,並將其作爲PNG圖像繪製爲圖形。我將通過AJAX提供這些數據,並且PHP會創建PNG圖像。現在,我如何從PHP獲取生成的PNG圖像作爲AJAX響應?代碼如下:使用AJAX從PHP獲取PNG圖像
PHP:
<?php
$data = json_decode($_POST['data']);
// Some code to calculate the next value in this series
plotRenderRegression($polynomialRegression, $coefficients, 0, 11 , $colorMap[ "Blue" ]);
header("Content-Type: image/png");
echo imagePNG($image);
?>
JS:
$.post({
dataType: "image/png",
url: "predict.php",
data: {
sent: true,
data: "[[1,0.63151965],[2,0.58534249],[3,0.43877649],[4,0.2497794],[5,0.07730788],[6,0.08980716],[7,0.11196788],[8,0.19979455],[9,0.4833865],[10,0.9923332]]"
},
success: function (img) {
console.log(img)
i = new Image();
i.src = img;
console.log(img);
$("#imgdiv").prepend(i);
},
error: function (error, txtStatus) {
console.log(txtStatus);
console.log('error');
}
});
控制檯輸出:
�PNG
IHDRX�Ao�NPLTE������00�������000������������333MMMfff���������������vD���IDATx��][��*�*>���o���$ ?$[��ɑq� Ι�����������2������Fp�;D33������c���وeĪF�iO̮H�����r*3'���[N
o~p#���X��ˀ���ub��T�X�,������q�.�R��}� �]��#æy����l}�
}:U���,�����'�w�W_�0S9ԡ�wl�0�עOfTc8qw��9,=�s����7��^��h�U�1b-��?��鎿G����Ag��}����7Gg��GY���R��4y� LE����8'o� �+L>A��ʻ�e�hry��سد�끷�j����`#�����)ժϜΟc-)_ck��� ���=2�W�rY�X�gY]���1�H�T�3�*�]'�V�T̼t$���ྑN��&�K���%qp�cuf���2}8����`�PA'VF%6�PoC-6!���ky����8䪏U�:������,�Ƌ�
�9Uby���W�
���共� .....
我在做什麼錯在這裏?
更新1:
我已經改變了JS代碼如下所示,但它仍然得到一個破碎的形象
success: function (data) {
$('#imgdiv').html('<img src="data:image/png;base64, ' + btoa(unescape(encodeURIComponent(data))) + '" />');
}
你看着這個答案http://stackoverflow.com/a/13265644/689579? – Sean
或這一個http://stackoverflow.com/a/10802497/689579? – Sean
查看http://stackoverflow.com/questions/12876000/how-to-build-pdf-file-from-binary-string-returned-from-a-web-service-using-javas/ – guest271314