首先,抱歉我的英语不好,我是意大利人。我对编程有点陌生,但对于我的办公室,我需要创建有点复杂的脚本(至少对我来说)。在解释问题之前,我将解释我在做什么。
我编写了一个 Canvas 脚本,它根据数据输入创建图像,然后将图像数据发送到 php 进行保存过程。问题是我还需要发送 js 变量的值 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
关于php - 从 Javascript Canvas 图像信息和一些变量传递到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16894152/