我提前道歉,因为这有点长。我已经试图解决这个问题一段时间没有成功,所以我想发布我的大部分代码,以便帮助我的神奇人物可以更好地了解我在做什么。在我的上一篇文章 - Cannot get .js to be called upon form POST中向我建议 - 我创建了一个新帖子
我有一个项目,所有代码都在一个页面上进行,html,php,javascript和一堆SQL查询。我试图摆脱这一点,使用单独的页面,并将AJAX纳入其中,这样我就可以更新数据库,这是页面的核心,无需刷新。
我有两个主要页面 - test.php 和 getuser.php ,以及两个较小的位, update.php 和 update.js
test.php是我首先加载的页面。它分为两个<div>
s,顶部div,其中包含一个SQL查询到我的数据库以选择一个用户,以及底部div,在从下拉菜单中选择用户时,启动脚本showUser(),并向getuser.php发送一个AJAX请求,以在下面加载页面的其余部分。
<?php session_start(); ?>
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="/bootstrapstyle.css">
<link rel="stylesheet" href="/toastr.css">
<script type="text/javascript" src="/toastr.js"></script>
<script type="text/javascript" src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<style type="text/css">
body {
padding-top: 50px;
padding-bottom: 20px;
}
</style>
<script type="text/javascript" src="/update.js"></script>
<script>
function showUser(str) {
if (str !==".PM") {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="home.php">HOME</a>
</div>
<div class="navbar-collapse collapse">
<form>
<ul class="nav navbar-nav">
<li>
<a>
<?php
include('./db.php');
$PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
?>
<span class="custom-dropdown custom-dropdown--red">
<select class="navbar-inverse" placeholder="PM Name" name="PMName" onchange="showUser(this.value)">
<?php
while ($row = mysqli_fetch_row($PM)) {
$selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
}
?>
</select>
</span>
</a>
</li>
</ul>
</form>
</div>
</div>
</div>
<div id="txtHint"><b>Select a name from the dropdown menu above...</b></div>
</body>
</html>
<?php session_start(); ?>
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="/bootstrapstyle.css">
<link rel="stylesheet" href="/toastr.css">
<script type="text/javascript" src="/toastr.js"></script>
<script type="text/javascript" src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<style type="text/css"> body { padding-top: 50px; padding-bottom: 20px; }
</style>
<script type="text/javascript" src="/update.js"></script>
</head>
<body>
<?php
$q = $_GET['q'];
include('./db.php');
$LimitStart = 0 ;
$LimitItems = 10 ;
//THIS IS THE SQL COMMAND THAT ACTUALLY GRABS THE CORRECT PM
$sqlPM= "SELECT * FROM report WHERE PMName = '".$q."' and REGNSB <> 0.000 ORDER BY TrackNumber ASC Limit $LimitStart,$LimitItems";
$result = mysqli_query($con, $sqlPM);
// THIS IS FOR THE PAGE COUNT TOTAL OF THAT SPECIFIC PM
$sqlCommand = "SELECT COUNT(*) FROM report where PMName = '".$q."' AND REGNSB <> 0.000";
$query = mysqli_query($con, $sqlCommand) or die(mysqli_error());
$pages = mysqli_fetch_row($query);
$totalPages = round($pages[0] / 10);
mysqli_free_result($query);
if (isset($_POST['previous'])) {
$postedLimit = (isset($_POST['previous']) ? (int) $_POST['previous'] : 0);
$prevLimit = 1;
$_SESSION['page'] = ((int) $nextLimit / 10)+1;
$result = mysqli_query($con, "SELECT * FROM report WHERE PMName = '$PMSelection' AND REGNSB <> 0.000 ORDER BY TrackNumber ASC Limit $LimitStart,$LimitItems");
}
if (isset($_POST['next'])) {
$postedLimit = (isset($_POST['next']) ? (int) $_POST['next'] : 0);
$nextLimit = $postedLimit + 10;
$_SESSION['page'] = ((int) $nextLimit / 10)+1;
$result = mysqli_query($con, "SELECT * FROM report WHERE PMName = '$PMSelection' AND REGNSB <> 0.000 ORDER BY TrackNumber ASC, RegNSB DESC Limit $nextLimit,$LimitItems");
}
if (isset($_SESSION['page'])) {
} else {
$_SESSION['page'] = 1 ;
}
?>
<!-- MAIN JUMBOTRON THAT LISTS THE TITLE OF THE PAGE AS WELL AS THE PAGE 1 OF X THING... -->
<div class="jumbotron">
<div class="container">
<h1 class="pull-left">DW1 Invoice-Backlog Report</h1>
<h2 class="pull-right"><?= $q ?></h2>
</div>
<div class="container">
<div class="test">
<div class="inner">
<form method="POST" action="">
Page <?= $_SESSION['page'] ?> of <?= $totalPages ?> :
<input class="button" type="submit" name="previous" value="START" onclick="this.value=<?php echo $prevLimit; ?>">
<input class="button" type="submit" name="next" value="NEXT" onclick="this.value=<?php echo $nextLimit; ?>">
</form>
</div>
</div>
</div>
<div class="container pull-right">
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-3 col-lg-12">
<form id="updateChanges" method="POST" action="update.php">
<div class="container pull-right">
<h2 class="pull-left">
<input class="button" name="update"<?= $LineID ?>" type="submit" id="update" value="UPDATE">
</h2>
</div>
<div id="tableRefresh">
<table id="box-table-a">
<tr>
<th>
..all my headers..........
</th>
</tr>
<?php
while ($row = mysqli_fetch_array($result)) {
$LineID = $row['LineID'];
$trackNumber = $row['TrackNumber'];
$PMName = $row['PMName'];
$RegNSB = number_format($row['RegNSB'], 0);
$TrackCount = $row['TrackCount'];
$TrackNSB = number_format($row['TrackNSB'], 0);
$TotalBacklog = number_format($row['TotalBacklog'], 0);
$AverageBacklog = number_format($row['AverageBacklogTrackMargin'] * 100, 2);
$RGPPercent = number_format($row['RGPPercent'] * 100, 2);
$PMComments = $row['PMComments'];
$PMMRecommendations = $row['PMMRecommendations'];
$Outcome = $row['Outcome'];
$NewGPPercent = $row['NewGPPercent'];
$AdditionalGP = $row['AdditionalGP'];
$PMM = $row['PMM'];
$NEDA = $row['NEDA'];
$InvoiceNumber = $row['InvoiceNumber'];
$InvCustEB = $row['InvCustEB'];
?>
<tr>
<td>
....all my rows...
</td>
</tr>
<?php
}
?>
$(function() {
// Get the form.
var form = $('#updateChanges');
// Set up an event listener for the contact form.
form.submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = form.serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData
});
});
});
<?php
include('./db.php');
$data = array(); //array to pass back the sum of PM Comments, PM Recs, Outcomes... etc....
for ($n = 0, $t = count($_POST['PMComments']); $n < $t; $n++) {
$UpdateValue = $_POST['Update'][$n];
$PMCommentsValue = $_POST['PMComments'][$n];
$PMMRecommendationsValue = $_POST['PMMRecommendations'][$n];
$OutcomeValue = $_POST['Outcome'][$n];
$NewGPPercentValue = $_POST['NewGPPercent'][$n];
$AdditionalGPValue = $_POST['AdditionalGP'][$n];
$LineID = $_POST['LineID'][$n];
$sqlUPDATE = "UPDATE report SET PMComments = '$PMCommentsValue' , PMMRecommendations = '$PMMRecommendationsValue' , Outcome = '$OutcomeValue' , NewGPPercent = '$NewGPPercentValue', AdditionalGP = '$AdditionalGPValue' WHERE LineID = $LineID ;";
?>
<div id="alerts">
<?php
echo $sqlUPDATE . "<br>"; //this echos back the entire SQL entry that will be made
?>
</div>
<?php
$doUPDATE = mysqli_query($con, $sqlUPDATE);
if (!$doUPDATE) {
die('Could not update data: ' . mysqli_error($con));
}
if ($OutcomeValue <> 'null') {
$sqlMOVE = "INSERT INTO results SELECT * FROM report WHERE LineID = $LineID ;" ;
$sqlDELETE = "DELETE FROM report where LineID = $LineID ;" ;
$doMOVE = mysqli_query($con, $sqlMOVE);
if (!$doMOVE)
{
die('Could not MOVE data: ' . mysqli_error($con));
}
$doDELETE = mysqli_query($con, $sqlDELETE);
if (!$doDELETE)
{
die('Could not DELETE data: ' . mysqli_error($con));
}
}
}
mysqli_close($con);
?>
现在,我首先加载test.php并从下拉菜单中选择一个名称,该名称使用getuser.php生成的表填充页面的下半部分。这是我的问题开始的地方。 在getuser.php页面上,我有3个按钮 - start
和next
按钮以及submit
按钮。 start
和next
按钮将我发送回开头(就好像我从头开始加载test.php)和update
按钮WORKS,但它加载update.php而不是加载update.js,重定向到update.php并成功处理它(这是我通过利用多页面AJAX环境试图避免的全部内容......)如果我加载getuser.php?q = John%20Doe 本身,这些按钮都完全按照我的设计工作。
我将此代码放在update.js文件的开头,因为我在test.php和getuser.php中都调用它:
$(document).ready(function(){
$("div").css("border", "3px solid red");
console.log("update.js loaded successfully");
});
只是为了确保我的.js文件正确加载。
如果正常加载页面(test.php),页面顶部标题周围会出现一个小红色边框 - 因此正在调用update.js,但是没有在getuser上调用它。之后加载的php,因为该页面上的div周围没有小红色边框。如果我直接加载getuser.php而不通过test.php,边框就在那里,一切正常。
当我开始讨论这个问题时,我必须跳过某些部分的学习,因为我不知道出了什么问题,或者我的一些代码仅在我直接加载页面时才起作用而不是&#34;内部&# 34;另一页。
答案 0 :(得分:0)
最大的问题是您加载到DOM中的HTML内容不会处理您包含的JavaScript文件。因此,您应该使用jQuery的.load()
来正确加载AJAX调用后面的页面。这将加载包含的JavaScript文件。
整个街区:
function showUser(str) {
if (str !==".PM") {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
变为:
function showUser(str) {
if (str !==".PM") {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
}
$("#txtHint").load( "getuser.php?q="+str );
}