【问题标题】:html5 Canvas signature pad error with xmlhttpRequest带有xmlhttpRequest的html5 Canvas签名板错误
【发布时间】:2015-01-24 02:18:33
【问题描述】:

我正在关注这个帖子:Can't get html5 Canvas signature pad to submit to database,这是一个很棒的签名脚本,但是当我尝试将它保存到 DB 时已经出现错误...控制台给了我这个错误:

Error: Failed to construct 'XMLHttpRequest': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

你能帮我用这部分 javascript 来修复它吗:

$("#saveSig").click(function saveSig() {
    //encode URI
    var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
    $("#imgData").html('Thank you! Your signature was saved');
    var ajax = XMLHttpRequest();
    ajax.open("POST", 'sign/signature.php');
    ajax.setRequestHeader('Content-Type', 'application/upload');
    ajax.send(sigData);
    $('#debug').html(sigData);
});

【问题讨论】:

    标签: javascript xmlhttprequest


    【解决方案1】:

    我已经找到答案了!

    这是画布中隐藏的输入:

    <input type="hidden" value="<?php echo $user_id; ?>" name="user_id" id="user_id" />
    

    下面是运行这个脚本的代码:

    $("#saveSig").click(function saveSig() {
        //encode URI
        var sigData = canvas.toDataURL("image/png");
        var user_id = $("#user_id").val();  //here the id is showed, like 1, 2, etc
        $("#firm").html("Thank you! Your signature was saved with the id: "+user_id);
        $("#debug").html(sigData);
        var ajax = new XMLHttpRequest(); 
        ajax.open("POST", "sign/signature.php",false);
    ajax.onreadystatechange = function() {
        console.log(ajax.responseText);
    }
    ajax.setRequestHeader("Content-Type", "application/upload");
    ajax.send("imgData="+sigData);
       // ajax.send("user_id"+user_id);  //here give me this error: InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.
    });
    

    数据库连接:

    <?php
      if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
      {
      $session_id = $_SERVER['REMOTE_ADDR'];
      // Get the data
      $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
    
    //$user_id = (isset($_POST['user_id'])) ? $_POST['user_id'] : ""; //not works
    //$user_id = $_POST['userId']; //not works
    
    $user_id = '1'; // when I put a number the id is saved
    
    // process your sigData here (e.g. save it in the database together with the user_id)
    
      // Remove the headers (data:,) part.
      // A real application should use them according to needs such as to check image type
      $filteredData=substr($imageData, strpos($imageData, ",")+1);
    
      // Need to decode before saving since the data we received is already base64 encoded
      $unencodedData=base64_decode($filteredData);
    
      //echo "unencodedData".$unencodedData;
      $imageName = "sign_" . rand(5,1000) . rand(1, 10) . rand(10000, 150000) . rand(1500, 100000000) . ".png";
      //Set the absolute path to your folder (i.e. /usr/home/your-domain/your-folder/
      $filepath = "../signature/" . $imageName;
    
      $fp = fopen("$filepath", 'wb' );
      fwrite( $fp, $unencodedData);
      fclose( $fp );
    
      //Connect to a mySQL database and store the user's information so you can link to it later
    
    include_once("CONN/configs.php");
            try{
        $statement = $conn->prepare("INSERT INTO SIGNATURE (`session`, `user_id`, `signature`) VALUES (?, ?, ?)");
        if ($statement->execute(array($session_id, $user_id, $imageName)));
    
            echo '<div class="alert alert-success">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>
            Firma con id: '.$user_id.' guardada correctamente.</div>';
        }
        catch (Exception $e) 
        {
            echo '<div class="alert alert-danger">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>
            Error al tratar de guardar la firma.</div>';
            die;
        }
    }
    ?>
    

    我希望有人会需要这个。

    最好的问候!

    【讨论】:

      【解决方案2】:

      错误信息说明了你应该做什么:你应该使用'new'操作符来构造'XMLHttpRequest'。

      在您创建 ajax 对象的位置,将 var ajax = XMLHttpRequest(); 更改为 var ajax = new XMLHttpRequest();

      由于您无论如何都在使用 jquery,因此您可以使用 jquerys ajax method 来发出 ajax 请求,而不是处理 browser specifics of XMLHttpRequest

      $("#saveSig").click(function saveSig() {
        //encode URI
        var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
        $.ajax({
          type: "POST",
          url: 'sign/signature.php',
          contentType: 'application/upload',
          data: sigData,
          success: function () {
            $("#imgData").html('Thank you! Your signature was saved');     
          }
        });
        $('#debug').html(sigData);
      });
      

      更新回应各位cmets:

      你必须明白,这个javascript和... click(function saveSig() {...}是在浏览器中执行的。所以你不应该在里面放任何 php,因为 php 必须由网络服务器执行。当您单击“#saveSig”元素时,浏览器会执行此功能,并通过调用$.ajax(...) 向后台的网络服务器发送一个新的HTTP POST 请求,调用url 'sign/signature.php'。该请求的响应数据可用于成功函数。下面是一个网络服务器 (php) 和浏览器 (javascript) 如何协同工作的示例。

      签名/signature.php

      <?php
      // read the request data:
      $sigData = (isset($_POST['data'])) ? $_POST['data'] : "";
      $user_id = (isset($_POST['UserId'])) ? $_POST['userId'] : "";
      
      // process your sigData here (e.g. save it in the database together with the user_id)
      
      //generate the response:
      echo "Successfully saved signature for user id: ".$user_id.".";
      ?>
      

      javascript:

      $("#saveSig").click(function saveSig() {
        //encode URI
        var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
        $.ajax({
          type: "POST",
          url: 'sign/signature.php',
          contentType: 'application/upload',
          data: {
            data: sigData,
            user_id: $('#user_id').val() // this get's the value from the hidden user_id input
          },
          success: function (responseData) {
            $("#imgData").html('Thank you!' + responseData);
          }
        });
        $('#debug').html(sigData);
      });
      

      也许 w3schools 的 AJAX Introduction 对你来说很有趣

      【讨论】:

      • 使用这个 ajax 方法如何添加
        &lt;input type="hidden" name="user_id" id="user_id" type="text" value="&lt;?php echo $user_id; ?&gt;"&gt; 这是我需要将其保存在数据库中的最后一部分
      • 谢谢那部分给我看 id 但在数据库中不要保存它...我将这些代码放在 signature.php 中:$user_id = (isset($_POST['Data'])) ? $_POST['Data'] : "";$user_id= (isset($_POST['user_id'])) ? $_POST['user_id'] : "";$user_id=$_POST['Data']; 和 @987654335 @ 并始终将其保存为 0.. 错误在哪里?
      • 所以如果我理解你的页面中有一个输入是由 php 生成的 &lt;input type="hidden" name="user_id" id="user_id" type="text" value="&lt;?php echo $user_id; ?&gt;"&gt; ?然后你想将该值与 sigData 一起发送到 signature.php?
      • 这是正确的,这部分是:var user_id = responseData; 我用这个修改:var user_id = &lt;?php echo $user_id; ?&gt;; 并告诉我 id...但在数据库中,id 没有
      • 这样你就可以用php动态生成你的javascript了。我不建议这样做,因为它不是很清楚,很容易让人困惑。我将更新我的答案,向您展示如何使用 ajax 请求发送用户 ID。
      猜你喜欢
      • 1970-01-01
      • 2013-06-05
      • 2014-04-21
      • 2023-03-19
      • 1970-01-01
      • 2012-08-09
      • 2011-06-14
      • 1970-01-01
      • 2017-08-18
      相关资源
      最近更新 更多