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

时间:2018-05-16 07:05:26

标签: javascript php sql ajax database

我试图通过Ajax将HTML和Javascript代码保存到数据库,但不知道如何优化这种方式。我不能只为变量编写所有代码,如字符串。你有另一个想法让它变得更简单吗?

<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>

这是 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 个答案:

答案 0 :(得分:0)

我使用jquery ajax和post方法:

<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>

并在php端更改代码:

<?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();
?>

另见answer

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

您将此功能添加到您的javascript代码并在网址中传递get参数:

(文档)$。就绪(函数(){     $( “#add_code”)。单击(函数(){

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

});

});