[英]Passing from Javascript canvas image info AND some vars to PHP
首先,对不起我的英语不好,我是意大利语。 我对编程有点陌生,但是对于我的办公室,我需要创建有点复杂的脚本(至少对我而言)。 在解释问题之前,我先解释一下我在做什么。
我编写了一个脚本,该画布根据数据输入创建图像,然后将图像数据发送到php进行保存。 问题是我还需要发送js vars的值1(在示例value1中)。 我不知道如何将这些信息与原始图像数据一起传递。 用于img绘图和保存的js代码。 我需要将value1传递给save.php
button.addEventListener("click",function(){
//saving the values of the form
var value1 = document.getElementById("value1").value;
//text on the canvas
var value1X = (maxWidth-ctx.measureText(value1).width)/2+500;
//drawing the inputed text on the canvas
ctx.drawImage(img,0,0);
ctx.fillText(value1,value1X,maxHeight);
//getting the image url and sending it to save.php for the saving process
var imageURL = c.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST", 'saving.php', false);
ajax.setRequestHeader('Content-Type','application/upload');
ajax.send(imageURL);
}, false);
这是PHP文件:
<?php
if (isset($GLOBALS[HTTP_RAW_POST_DATA])) {
$imageData = $GLOBALS[HTTP_RAW_POST_DATA];
$imageData = str_replace('data:image/png;base64,', '', $imageData);
$imageData = str_replace(' ', '+', $imageData);
$data = base64_decode($imageData);
//here i need the value1 value from the javascript
$dirname = "value1";
$filename = "header_top.png";
$newdir = mkdir($dirname);
$path = ("the/path/to".$dirname."/");
$fp = fopen($path.$filename, 'wb');
fwrite($fp, $data);
fclose($fp);
}
我希望我能够自我解释,以便您可以帮助我。
非常感谢你。
编辑:我想我明白了,我的意思是目前它起作用了,但是我不知道它是否正确。 事实是,我正在调用一个php文件,因此我简单地在URL“?dir =” + value1的末尾添加了它,并且可以正常工作。
ajax.open("POST", 'saving.php?dir='+value1, false);
ajax.setRequestHeader('Content-Type','application/upload');
ajax.send(imageURL);
在php文件中,我只需调用$ _GET ['dir']即可获取该值。
@hendrik非常感谢您的回答,不幸的是我无法与json一起使用,也许是因为我不知道。
无论如何,如果有人知道更好的方法会很好。
我认为使用JSON是将数据发送到PHP文件的好方法。 这样,您可以将多个变量存储在对象或数组中。
// Store your data in an Object
var imageData = {
url: 'http://adsadsf.com',
name: 'foobar.gif',
width: 500,
height: 400,
directory: 'img/'
}
var ajax = new XMLHttpRequest();
ajax.open("POST", 'saving.php', false);
// Send the imageData object as JSON
ajax.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
ajax.send(JSON.stringify(imageData));
不幸的是,我对PHP的了解不足,无法确切解释如何处理接收到的JSON数据,但是我想您可以使用json_decode
方法。
有关JSON的更多信息: http : //www.json.org/js.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.