【问题标题】:Update SQL Query with populated variables from AJAX functions over multiple PHP Pages使用来自多个 PHP 页面的 AJAX 函数的填充变量更新 SQL 查询
【发布时间】:2019-10-07 22:28:57
【问题描述】:

我试图就这个问题寻求帮助。

总而言之 Q:它不会像这样逐步更新我的数据库条目,我认为它可以如何完成。

它有点难以解释,但我尝试用最少且可读的代码逐步解释它。我使用原始代码,很难将其转换为可重现的示例。

A.1 页面 ma_aktuelle_ReadOut.php 有一个php部分

 <?php echo "<a href='ma_Testende.php?TestergebnisID=&TestaufstellungID=". $row['TestaufstellungID']."&TesterID=".$row['TesterID']."' title='Test stoppen' data-toggle='tooltip' class='stoppen'>   <span class='glyphicon glyphicon-stop'></span></a>";
?>

当我单击此链接时,会调用以下 javascript 函数并问我“真的停止了吗?”

<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
  $("a.stoppen").click(function(e){
   if(!confirm('Wirklich stoppen?')){
    e.preventDefault();
    $('.alert').show()
    return false;
    }
    return true;
            });
        });
</script>
<style>
 .alert {
  display: none;
    }
</style>

当我点击“是”时,它会打开第二个页面。

一个 2 页 ma_Testende.php 此页面上有 2 个 AJAX JS 函数。 第一个 Ajax 是通过 type:get 从下一页请求“基准”并等待成功(参见第 B 页 3):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">

/* function to get Stoptime for Cycle from DB.TesterCycleCount zu erhalten  */ 
$(document).ready(async function(){
var Datum;
var TesterID = "<?php echo $_GET['TesterID']; ?>"; /* value from TesterID */ 
await $.ajax({ /* First Ajax function */
            url: 'ma_get-TesterID_Testende.php',
            type: 'get', 
            data: {TesterID:TesterID}, 
            dataType: 'json',
            success:function(response){ 
                var CID = response['CID'];
                Datum = response['Datum'];
                console.log(response);
            },
             error: function(jqxhtt, status, exception) {
                 console.log(exception);
         alert('Exception:', exception)
            }
        });
console.log();
        var TestaufstellungID = "<?php echo $_GET['TestaufstellungID']; ?>";
         $.ajax({ /* Second Ajax function */
            url: 'ma_TestendeSQL.php',
            type: 'get', 
            data: {TestaufstellungID:TestaufstellungID, Datum: Datum}, 
            dataType: 'json',
            success:function(data){ 
            alert('Successfully called');
     },
     error: function(jqxhr, status, exception) {
         console.log(exception);
         alert('Exception:', exception)
            }
        });
        });
</script>

B 3 页面 ma_get-TesterID_Testende.php

<?php
$cinfo = array(
    "Database" => $database,
    "UID" => $username,
    "PWD" => $password
);
$conn = sqlsrv_connect($server, $cinfo);
                $sqlreadZeit = "Select TOP 1 CID,Datum from DB.dbo.TesterCycleCount where TesterID = '".$_GET['TesterID']."' order by Datum DESC";
                $result1 = sqlsrv_query($conn, $sqlreadZeit);
                $zeiten_arr = array();
                while ($row = sqlsrv_fetch_array($result1, SQLSRV_FETCH_ASSOC)) {
                $CID = $row['CID'];
                $Datum = $row['Datum']->format('d.m.Y h:m:s');
                $zeiten_arr[] = array("CID" => $CID, "Datum" => $Datum);
                                }
    header('Content-type: application/json');
  echo json_encode($zeiten_arr); 
?>

在“基准”后面调用第二个 AJAX(参见第 A 页 2) 使用“Datum”和“TestaufstellungID”作为变量,应该调用下一页并使用填充的变量更新数据库条目。

B. 4 页 ma_TestendeSQL.php

<?php
$cinfo = array(
    "Database" => $database,
    "UID" => $username,
    "PWD" => $password
);
$conn = sqlsrv_connect($server, $cinfo);

$TestaufstellungID = $_GET['TestaufstellungID'];
$Testende= $_GET['Datum'];
$Testdatum = date('Y-d-m');

$stop = $connection->prepare("WITH UpdateTestende AS (
  SELECT TOP 1  * from DB.dbo.Testergebnisse 
  WHERE TestaufstellungID = :TestaufstellungID
  ORDER BY TestergebnisID DESC 
)
update UpdateTestende 
set Testende = :Testende,
Datum = :Testdatum");
$stop->execute(array(':TestaufstellungID' => $TestaufstellungID, ':Testdatum' => $Testdatum, ':Testende' => $Testende));

    header('Content-type: application/json');
?>

php 变量$Testende 从 Ajax 函数中获取填充的“基准”。总而言之,它应该是更新,当我单击链接(页面 A 1)我的数据库条目与填充的“基准”,这是我从 SQL 查询(页面 A 2)的第一个 Ajax 调用(页面 A 2)中获得的( Page B 3) 回到第二个 AJAX Call (Page A 2) 比用数据:{TestaufstellungID:TestaufstellungID, Datum: Datum} 到最后一页 (Page B 4)

但它不会像这样一步一步地更新我的数据库条目,我认为它可以如何完成。

封装的 SQL 代码工作正常。使用代码header('Content-type: application/json');,当我点击来自 (Page A 1) 的链接时,浏览器会告诉我以下信息

SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符

这就是为什么我发布了所有步骤,我认为变量没有直接传递到下一页或者它们是空的,因为代码没有以正确的顺序执行服务器/客户端 PHP/JS 或异步问题.. . console.log 什么也没告诉我。目前我不知道从哪里开始调试?

希望有人可以帮助我。谢谢

编辑:我很确定 ajax 调用是空的,但我没有看到值在哪一步变空

编辑2: AJAX 调用为空或未启动。 进一步调查:Ajax 用空异常提醒我错误部分,而不提醒我成功部分。所以它不会转到页面 ma_get-TesterID_Testende.php 或者它不会返回 Datum 。 不能启用跨站点脚本是问题吗?

但在另一个页面中,类似的 Ajax 调用工作正常。

$(document).ready(function(){

var TesterID = "<?php echo $_GET['TesterID']; ?>"; /* value der Tester erhalten */ 

        $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */

                var len = response.length;

                $("#Teststart").empty(); /* Die erhaltenden Daten werden bei der ID angezeigt */
                for( var i = 0; i<len; i++){
                    var CID = response[i]['CID'];
                    var Datum = response[i]['Datum'];

                    $("#Teststart").append("<option value='"+Datum+"'>"+Datum+"</option>");

                }
            }
        });


    $("#TesterID").change(function(){ /* Wenn du änderst und vom Select Feld auswählst */
        var TesterID = $(this).val(); /* value der Tester erhalten */ 

        $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */

                var len = response.length;

                $("#Teststart").empty(); /* Die erhaltenden Daten werden bei der ID angezeigt */
                for( var i = 0; i<len; i++){
                    var CID = response[i]['CID'];
                    var Datum = response[i]['Datum'];

                    $("#Teststart").append("<option value='"+Datum+"'>"+Datum+"</option>");

                }
            }
        });
    });

});

在本例中,当我从下拉选择表单中更改值时,Ajax 调用开始。有区别吗?

这个 Ajax 应该如何工作我尝试在我的另一个问题中逐步解释,我的应用程序应该如何执行。

Update SQL Query with populated variables from AJAX functions over multiple PHP Pages

编辑 3: jQuery版本: https://code.jquery.com/jquery-3.4.1.js

【问题讨论】:

  • @kevinSpaceyIsKeyserSöze 你能解释得更深入一点吗,我是 AJAX 的新手。如果我不需要解析它,我该如何检查它?
  • 只需将其分配给没有myValue = JSON.parse(myValue) 的变量,而只需使用myValue
  • JSON.parse({}) 在浏览器中尝试此行,它将“准确”显示您的错误。然后你可以试试这条线JSON.parse("{}")。这就是为什么我认为它已经被解析了。
  • 我的代码中没有使用variable= JSON.parse()
  • @kevinSpaceyIsKeyserSöze 我应该在控制台的哪个页面上使用它?我试图在 Ajax 页面上使用它(A 2)在 Firefox 中,由于内容安全策略,我无法使用您的代码在谷歌浏览器中它告诉我:VM63:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (&lt;anonymous&gt;) at &lt;anonymous&gt;:1:6

标签: javascript php jquery sql-server ajax


【解决方案1】:

另一种选择是使用 $_SESSION 超全局;我提供它是因为这个问题被标记为 PHP 而不是 AJAX/JSON,并避免 JSON 值或数组的编码解码常见问题。如果可以,请更改策略并使用客户端广播数据并在错误响应事件中停止正常流程。

使用已启动的 session_start(),您可以使用 $_SESSION 中的内部临时数组来逐步附加/分离数据,在此示例中为“step”数组,如下所示:

<?php
// step 1
$_SESSION['step'][1]['TesterID']            = 64;
$_SESSION['step'][1]['var2']                = 'bar';
// step 2
$_SESSION['step'][2]['TestaufstellungID']   = 65;
$_SESSION['step'][2]['var4']                = 100;
$_SESSION['step'][2]['var5']                = 256.04;
?>

当您通过 AJAX 发送数据时,无需将其转换为 JSON,因为您可以使用 $_POST 对象。同时,响应可以为您提供 JSON 格式的每个 $_SESSION['step'] 值。

<?php
header("Content-type:application/json")
// conditions goes here
if ( $conditions == true ) {
    echo json_encode($_SESSION['step']);
}
?>

这样,考虑到是一个“逐步”的过程,您可以选择在每一步中保存一个更新的 json_encode() 对象,或者使用会话超全局只在过程完成时保存它,考虑所有“步骤”数组或者只是相关的值,在这种情况下是用户 ID

https://www.php.net/manual/es/reserved.variables.session.php

https://www.php.net/manual/es/function.session-id.php

https://www.php.net/manual/es/function.json-encode.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2015-09-05
    • 1970-01-01
    相关资源
    最近更新 更多