【问题标题】:How to send code to database with AJAX如何使用 AJAX 将代码发送到数据库
【发布时间】:2018-10-26 03:00:27
【问题描述】:

我尝试通过 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();
?>

【问题讨论】:

标签: javascript php sql ajax database


【解决方案1】:

我会使用带有 post 方法的 jquery ajax:

<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 代码中并在 url 中传递 get 参数:

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

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

});

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-16
    • 2013-09-14
    • 1970-01-01
    • 2014-09-15
    • 2015-12-15
    • 2014-09-26
    • 1970-01-01
    • 2013-08-28
    相关资源
    最近更新 更多