将这些脚本组合在一起工作,Javascript/AAJAX和PHP

Combine these scripts to work together, Javascript/AJAX and PHP

本文关键字:Javascript AAJAX PHP 工作 脚本 组合 在一起      更新时间:2023-09-26

我正在学习这里涉及的所有语言,目前正在努力将两个脚本组合起来完成一项任务。

我希望能够从表单选项列表中选择一个分支,将该选项中的值发送到php脚本以查询数据库。然后,从数据库返回的信息将用于使用第二个脚本加载的页面。

Jquery/AAJAX script one-当前用于使用从用户选择中收集的值将php页面加载到DIV中。

<script>
    $(document).ready(function(){
        function loadBranch(branch) {
            if (branch) {
        $('div#content2').load('../../procedures/'+ branch +'/ClientCalls/' + branch + '-Bookings.php');
        }
    }
    $('select[name=branch]').on('change', function() {
        loadBranch($(this).val());            
        });
    loadBranch($('select[name=branch]').val());
    });
</script>

我尝试使用的第二个脚本填充上一个脚本加载的页面。

<script>
$(document).ready(function(){
    $('select[name=branch]').on('change', function() {var branchGet = this.options[this.selectedIndex].value
        console.log(branchGet); 
        $.ajax({                                     
            url: '../../procedures/'+ branchGet +'/ClientCalls/' + branchGet + '-Bookings.php',
            data: {branchGet: branchGet},
            type: 'GET',
            dataType: 'json',
            success: function(data)
            {
                if(data == 'success'){
                    location.reload();
                }
            }
        });
    });
});
</script>

第二个脚本也在发送信息的php页面。

<?php
$user = '';
$pass = '';
try {
$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$branch = $_GET['branchGet'];
$true = 1;
$contactList = $DBH->prepare('SELECT contactName, contactNumber FROM branchcontact WHERE branch = ? AND inUse = ?');
$contactList->execute(array($branch, $true));
$contactResult = $contactList->fetchAll(PDO::FETCH_ASSOC);
<div><p><h4>First Contact</h4> <?php echo $contactResult['0']['contactName'] ." ".$contactResult['0']['contactNumber'] ?></p></div>
$success = 'success';
echo json_encode($success);
}
catch(Exception $e) {
echo 'Error: '.$e->getMessage();
}
?>

第二个脚本中的console.log显示选择了正确的分支,但是,我收到一个错误,说明PHP文件中的branchGet是和"Undefined Index",脚本失败了。由于变量为空,我无法查询数据库。

有人能告诉我正确的方向吗?因为我现在有点困惑。

提前干杯,

闪烁

如果在这一行上出现错误

$branch=$_GET['branchGet'];

这意味着没有设置GET变量,因此在PHP作为GET变量的资源提供的$_GET数组中不存在该变量的索引。

Get变量始终编码在URL中。分支机构?branchGet=URL的某个值。除非有您尚未发布的代码,否则$_GET变量包含任何

  1. 在浏览器中打开开发人员工具,查看XHR请求。验证发布到php脚本的URL是否以Bookings.php结尾?branchGet=某事如果是这样,那么错误就在PHP方面。如果不是,它在jquery方面。

  2. 我真的看不出PHP上有什么问题,但错误表明请求URL丢失了?branchGet=URL中的某些内容。