我每隔5秒运行一次我的javascript来调用update.php文件(希望将base64代码添加到mysql中 - 虽然还没弄清楚)。
目前,我只是将base64代码写到名为 debugConsole 的文本区域。
我只是不知道我应该如何将javascript变量传递给我的php更新文件。
HTML:
<script type="text/javascript">
function saveViaAJAX()
{
var testCanvas = document.getElementById("testCanvas");
var canvasData = testCanvas.toDataURL("image/png");
var postData = "canvasData="+canvasData;
var debugConsole= document.getElementById("debugConsole");
debugConsole.value=canvasData;
//alert("canvasData ="+canvasData );
var ajax = new XMLHttpRequest();
//ajax.open("POST",'testSave.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
//ajax.setRequestHeader('Content-TypeLength', postData.length);
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
//alert(ajax.responseText);
// Write out the filename.
document.getElementById("debugFilenameConsole").innerHTML="Saved as<br><a target='_blank' href='"+ajax.responseText+"'>"+ajax.responseText+"</a><br>Reload this page to generate new image or click the filename to open the image file.";
}
}
ajax.send(postData);
}
setInterval(function() { saveViaAJAX(); }, 5000);
</script>
<script language='javascript' type='text/javascript'>
//Every 5 seconds calls php update
//syncronized jax:
function myjax() {
oXhr = new XMLHttpRequest();
oXhr.open("POST", "update.php?game=<?php echo $game; ?>", false);
oXhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
oXhr.send(null);
}
//set an interval each 5 seconds to call your myjax method
setInterval(function() { myjax(); }, 5000);
</script>
</head>
<div>
<canvas id="testCanvas" width="300" height="300"></canvas>
</div>
<div>
<textarea id="debugConsole" rows="10" cols="60">Data</textarea>
</div>
<script type="text/javascript">
// This portion of the code simply draws random circles into the canvas (it has nothing todo with saving the canvas).
var canvas = document.getElementById("testCanvas");
if (canvas.getContext)
{
var canvasContext = canvas.getContext("2d");
for (i=0; i<150; i++)
{
canvasContext.fillStyle="rgb("+(parseInt(Math.random()*255))+","+(parseInt(Math.random()*255))+","+(parseInt(Math.random()*255))+")";
canvasContext.beginPath();
canvasContext.arc(Math.random()*350,Math.random()*350,Math.random()*20, 0,Math.PI*2,true);
canvasContext.fill();
}
}
</script>
PHP:
<?php
$random = rand();
$game = $_GET["game"];
mysql_query("UPDATE paint_s SET paint_points='$random' WHERE id ='$game'") or die(mysql_error());
echo "Updated";
?>
抱歉,由于我缺乏知识,我一直在做一些教程,只是试图扩展教程。
答案 0 :(得分:0)
您要做的第一件事是打开您的请求
ajax.open("POST",'testSave.php',true);
然后想要将您的数据发送为application/x-www-url-form-encoded
,因此请将其设置为内容类型
ajax.setRequestHeader('Content-Type', 'application/x-www-url-form-encoded');
要确保您的数据已正确编码,请使用encodeURIComponent
var postData = "canvasData="+encodeURIComponent(canvasData);
您还应该检查状态以查看请求是否真的超过了
if (ajax.readyState == 4)
{
if (ajax.status == 200){
//success
}
else{
//failure
}
}
我不知道是否每隔5秒保存一次base64编码图像是个好主意。