从Javascript画布图像信息和一些变量传递到PHP

从Javascript画布图像信息和一些变量传递到PHP,php,javascript,canvas,Php,Javascript,Canvas,首先,对不起我的英语不好,我是意大利人。我对编程有点陌生,但对于我的办公室,我需要创建有点复杂的脚本(至少对我来说)。在解释问题之前,我先解释一下我在做什么 我编写了一个画布脚本,从数据输入创建一个图像,然后将图像数据发送到php进行保存。问题是我还需要发送一个js变量的值1(在示例value1中)。我不知道如何将这些信息与原始图像数据一起传递。 img绘图和保存的js代码。我需要将值1传递给save.php button.addEventListener("click",function(){

首先,对不起我的英语不好,我是意大利人。我对编程有点陌生,但对于我的办公室,我需要创建有点复杂的脚本(至少对我来说)。在解释问题之前,我先解释一下我在做什么

我编写了一个画布脚本,从数据输入创建一个图像,然后将图像数据发送到php进行保存。问题是我还需要发送一个js变量的值1(在示例value1中)。我不知道如何将这些信息与原始图像数据一起传递。 img绘图和保存的js代码。我需要将值1传递给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文件中,我只需调用$_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的更多信息:

欢迎来到StackOverflow!我认为您可能没有得到任何答案的原因是您的问题和代码都非常冗长。我建议缩短对您的问题的描述,并将代码简化为与您的问题密切相关的代码。好的,非常感谢。我马上把它缩短。
// 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));