dongwei4103 2018-05-16 07:05
浏览 96
已采纳

如何使用AJAX将代码发送到数据库

I tried to save a HTML and also Javascript codes to Database by Ajax, but don't know how to optimize this way. I can't just write all codes like Strings for the variable. Do you have another idea to make it simpler ?

<script type="text/javascript">
  $(document).ready(function(){
    $("#add_code").click(function(){
        var addCode = "Here is Javascript code";
        $.get("includes/dashboard/addcode.php", {addCode:addCode
        },function(data){
        });
    });
  });
</script>

And this is the addcode.php

<?php
 require('database/connect_database.php');
  session_start();
   $addCode = $_GET['addCode']; 
   $codename = $_SESSION['codename'];
   $stmt = $pdo->prepare("INSERT INTO code (codename, w_code) VALUES ('$codename','$addCode')");
   $stmt->execute();
?>
  • 写回答

1条回答 默认 最新

  • dongyuli4538 2018-05-16 07:10
    关注

    I'd use jquery ajax with post method:

    <script type="text/javascript">
      $(document).ready(function(){
        $("#add_code").click(function(){
    
            var addCode = "Here is Javascript code";
            $.ajax({
                url: 'includes/dashboard/addcode.php',
                type: 'post',
                data: {addCode: addCode},
                success: function(response){
                    console.log(response);
                },
                error: function(error){
                    console.log(error.responseCode);
                }
            });
    
        });
      });
    </script>
    

    and change code also on php-side:

    <?php
     require('database/connect_database.php');
      session_start();
       $addCode = $_POST['addCode']; 
       $codename = $_SESSION['codename'];
       $stmt = $pdo->prepare("INSERT INTO code (codename, w_code) VALUES ('$codename','$addCode')");
       $stmt->execute();
    ?>
    

    also see this answer:

    function httpGet(theUrl)
    {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
        xmlHttp.send( null );
        return xmlHttp.responseText;
    }
    

    you add this function to your javascript code and pass get parameters in the url:

    $(document).ready(function(){ $("#add_code").click(function(){

        var addCode = "Here is Javascript code";
        console.log(httpGet('includes/dashboard/addcode.php?addCode='+addCode));
    
    });
    

    });

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题