drn9573 2014-04-03 11:51
浏览 68
已采纳

Ajax responseText为空

Over the last couple of days I have learnt about the canvas-element and now I want to add AJAX to save the canvas to the server. Specifically, I am letting users draw on the canvas and when they are finished they click a button and the canvas is sent and saved to the server. The code below works excellently.

Javascript:

var testCanvas = document.getElementById('imageView');
var canvasData = testCanvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.onreadystatechange=callback();
ajax.open("POST",'script.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.send("canvasData"+canvasData );
function callback (){alert ('it works!');}

PHP-code:

<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
    // Get the data
    $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];

    $filteredData=substr($imageData, strpos($imageData, ",")+1);

    $unencodedData=base64_decode($filteredData);
    $fp = fopen( 'images/'.uniqid().'.png', 'wb' );
    fwrite( $fp, $unencodedData);
    fclose( $fp );
        echo "saved";
}
  else{

  echo "no raw data";
  }
?>

However, I would like to have the filename and location returned to the script, so that I can present the server-side image and location to the user. I have not adjusted the php-code yet, because using the following returns an empty string:

function callback () { alert (ajax.responseText);}

I have searched and the topic seems to have been addressed a couple of times without resulting in me being able to fix the above.

Where I am going wrong?

  • 写回答

1条回答 默认 最新

  • duankuai6586 2014-04-03 11:52
    关注

    reference functions, don't call them, and wait for the readyState to return 4

    var testCanvas = document.getElementById('imageView');
    var canvasData = testCanvas.toDataURL("image/png");
    var ajax = new XMLHttpRequest();
    
    ajax.onreadystatechange = callback;
    
    ajax.open("POST",'script.php',true);
    ajax.setRequestHeader('Content-Type', 'canvas/upload');
    ajax.send("canvasData"+canvasData );
    
    function callback (){
        if (ajax.readyState == 4) {
            alert(ajax.responseText);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向