drn9573
2014-04-03 11:51 阅读 58

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 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);
        }
    }
    
    点赞 评论 复制链接分享

相关推荐