AJAX でテーブルを生成した後、JavaScript に問題があります。ユーザーが挿入した値を含むテーブルを生成しています。値は、ローカルで実行される SQL EXPRESS 2012 データベースから取得されます。値が取得されると、文字列に格納されます。その文字列は index.thml に送り返されています。すべての結果の取得は、validate.php によって行われています。
通常のテーブルでコードを試してみましたが、魅力的に機能します。しかし、生成されたテーブルを使用するたびに、javascript の実行を拒否しているようです。
これについての私の個人的な考えは、ページが読み込まれたときにテーブルが存在しないためです。ページがロードされた後にテーブルが作成されるため、javascript が正しく実行されません。マウスオーバー時の行の強調表示にも同じ問題がありました。tr.mouseover で mouseover 関数を呼び出すことで、この問題を解決しました。
正直なところ、私は ajax と JavaScript を初めて使用するので、現在持っているものはほとんどすべてインターネットから入手したものです。私はすべてが何を意味するかを知っており、プロジェクトのコードを変更しました。私は数日間立ち往生しているので、皆さんがこれに明るい光を当ててくれることを本当に願っています.
それでは始めましょう:
私のindex.html:
<html>
<head>
<title>ESL Checking Tool</title>
<link href="style/style.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="ajaxrequest.js"></script>
<script type="text/javascript">
function callAjax(method, value, target)
{
if(encodeURIComponent)
{
var req = new AjaxRequest();
var params = "method=" + method + "&value=" + encodeURIComponent(value) + "&target=" + target;
req.setMethod("POST");
req.loadXMLDoc('validate.php', params);
}
}
</script>
<script type="text/javascript">
function mouseover()
{
var message = $('#message');
var tr = $('#table_id').find('tr');
tr.hover(
function()
{ //mouseover
$(this).addClass('row-highlight');
var values = '';
var tds = $(this).find('td');
$.each(tds, function(index, item)
{
values = values + 'td' + (index + 1) + ':' + item.innerHTML + '<br/>';
});
message.html(values);
},
function()
{ // mouseout
$(this).removeClass('row-highlight');
message.html('');
})
}
</script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body id="dt_example">
<form method="POST" action="non-Ajax form handler" onsubmit="return checkForm(this;">
<fieldset>
<legend>ESL Checkup Form</legend>
<p>Product: <input type="text" size="32" id="product" name="product" onkeyup="if(this.value != '') callAjax('checkProduct', this.value, this.id);">
<input id="valid_product" type="checkbox" disabled name="valid_product"></p>
<div id="rsp_product">
</div>
<p>Barcode: <input type="text" size="32" id="barcode" name="barcode" onkeyup="if(this.value != '') callAjax('checkBarcode', this.value, this.id);">
<input id="valid_barcode" type="checkbox" disabled name="valid_barcode"></p>
<div id="rsp_barcode"><!-- --></div>
<p>ESL: <input type="text" size="32" id="email" name="email" onkeyup="if(this.value != '') callAjax('checkEmail', this.value, this.id);">
<input id="valid_email" type="checkbox" disabled name="valid_email"></p>
<div id="rsp_email"><!-- --></div>
</fieldset>
</form>
<div id="message">
</div>
<a href="#" class="topopup">Click Here Trigger</a>
<div id="toPopup">
<div class="close"></div>
<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!--your content start-->
<p>
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
feugiat vitae, ultricies eget, tempor sit amet, ante. </p>
<br />
<p>
Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. </p>
<p align="center"><a href="#" class="livebox">Click Here Trigger</a></p>
</div> <!--your content end-->
</div> <!--toPopup end-->
<div class="loader"></div>
<div id="backgroundPopup"></div>
</body>
</html>
私のスタイル/style.css:
/*
author: istockphp.com
*/
#backgroundPopup {
z-index:1;
position: fixed;
display:none;
height:100%;
width:100%;
background:#000000;
top:0px;
left:0px;
}
#toPopup {
font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
background: none repeat scroll 0 0 #FFFFFF;
border: 10px solid #ccc;
border-radius: 3px 3px 3px 3px;
color: #333333;
display: none;
font-size: 14px;
left: 50%;
margin-left: -402px;
position: fixed;
top: 20%;
width: 800px;
z-index: 2;
}
div.loader {
background: url("../img/loading.gif") no-repeat scroll 0 0 transparent;
height: 32px;
width: 32px;
display: none;
z-index: 9999;
top: 40%;
left: 50%;
position: absolute;
margin-left: -10px;
}
div.close {
background: url("../img/closebox.png") no-repeat scroll 0 0 transparent;
bottom: 24px;
cursor: pointer;
float: right;
height: 30px;
left: 27px;
position: relative;
width: 30px;
}
span.ecs_tooltip {
background: none repeat scroll 0 0 #000000;
border-radius: 2px 2px 2px 2px;
color: #FFFFFF;
display: none;
font-size: 11px;
height: 16px;
opacity: 0.7;
padding: 4px 3px 2px 5px;
position: absolute;
right: -62px;
text-align: center;
top: -51px;
width: 93px;
}
span.arrow {
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 7px solid #000000;
display: block;
height: 1px;
left: 40px;
position: relative;
top: 3px;
width: 1px;
}
div#popup_content {
margin: 4px 7px;
}
.row-highlight {
background-color: #0099FF;
}
私のajaxrequest.js:
function AjaxRequest()
{
var req;
var method="GET";
var nocache=false;
var handler;
this.loadXMLDoc=function(url,params)
{
if(window.XMLHttpRequest)
{
try
{
req=new XMLHttpRequest();
}
catch(e)
{
req=false;
}
}
else if(window.ActiveXObject)
{
try
{
req=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
req=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
req=false;
}
}
}
if(req)
{
if(!handler)handler=processReqChange;req.onreadystatechange=handler;if(nocache)
{
params+=(params!='')?'&'+(new Date()).getTime():(new Date()).getTime();
}
if(method=="POST")
{
req.open("POST",url,true);
req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
req.send(params);
}
else
{
if(params)url+="?"+ params;req.open(method,url,true);req.send(null);
}
return true;
}
return false;
}
this.setMethod=function(newmethod)
{
method=newmethod.toUpperCase();
}
this.nocache=function()
{
nocache=true;
}
this.setHandler=function(fn)
{
handler=fn;
}
this.getResponse=function()
{
return req;
}
var getNodeValue=function(parent,tagName)
{
var node=parent.getElementsByTagName(tagName)[0];
return(node&&node.firstChild)?node.firstChild.nodeValue:'';
}
var processReqChange=function()
{
if(req.readyState==4&&req.status==200)
{
var response=req.responseXML.documentElement;
var commands=response.getElementsByTagName('command');
for(var i=0;i<commands.length;i++)
{
method=commands[i].getAttribute('method');
switch(method)
{
case'alert':var message=getNodeValue(commands[i],'message');
window.alert(message);
break;
case'setvalue':var target=getNodeValue(commands[i],'target');
var value=getNodeValue(commands[i],'value');
if(target&&value!=null)
{
document.getElementById(target).value=value;
}
break;
case'setdefault':var target=getNodeValue(commands[i],'target');
if(target)
{
document.getElementById(target).value=document.getElementById(target).defaultValue;
}
break;
case'focus':var target=getNodeValue(commands[i],'target');
if(target)
{
document.getElementById(target).focus();
}
break;
case'setcontent':var target=getNodeValue(commands[i],'target');
var content=getNodeValue(commands[i],'content');
if(target&&(content!=null))
{
document.getElementById(target).innerHTML=content;
}
break;
case'setstyle':var target=getNodeValue(commands[i],'target');
var property=getNodeValue(commands[i],'property');
var value=getNodeValue(commands[i],'value');
if(target&&property&&(value!=null))
{
document.getElementById(target).style[property]=value;
}
break;
case'setproperty':var target=getNodeValue(commands[i],'target');
var property=getNodeValue(commands[i],'property');
var value=getNodeValue(commands[i],'value');
if(value=="true")value=true;
if(value=="false")value=false;
if(target&&document.getElementById(target))
{
document.getElementById(target)[property]=value;
}
break;
default:window.console.log("Error: unrecognised method '"+ method+"' in processReqChange()");
}
}
}
}
}
私のscript.js:
/*
author: istockphp.com
*/
jQuery(function($) {
$("a.topopup").click(function() {
loading(); // loading
setTimeout(function(){ // then show popup, deley in .5 second
loadPopup(); // function show popup
}, 500); // .5 second
return false;
});
$("tr#row-clck").click(function() {
loading(); // loading
setTimeout(function(){ // then show popup, deley in .5 second
loadPopup(); // function show popup
}, 500); // .5 second
return false;
});
/* event for close the popup */
$("div.close").hover(
function() {
$('span.ecs_tooltip').show();
},
function () {
$('span.ecs_tooltip').hide();
}
);
$("div.close").click(function() {
disablePopup(); // function close pop up
});
$(this).keyup(function(event) {
if (event.which == 27) { // 27 is 'Ecs' in the keyboard
disablePopup(); // function close pop up
}
});
$("div#backgroundPopup").click(function() {
disablePopup(); // function close pop up
});
$('a.livebox').click(function() {
alert('Hello World!');
return false;
});
/************** start: functions. **************/
function tablerowclick() {
loading(); // loading
setTimeout(function(){ // then show popup, deley in .5 second
loadPopup(); // function show popup
}, 500); // .5 second
return false;
}
function loading() {
$("div.loader").show();
}
function closeloading() {
$("div.loader").fadeOut('normal');
}
var popupStatus = 0; // set value
function loadPopup() {
if(popupStatus == 0) { // if value is 0, show popup
closeloading(); // fadeout loading
$("#toPopup").fadeIn(0500); // fadein popup div
$("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8
$("#backgroundPopup").fadeIn(0001);
popupStatus = 1; // and set value to 1
}
}
function disablePopup() {
if(popupStatus == 1) { // if value is 1, close popup
$("#toPopup").fadeOut("normal");
$("#backgroundPopup").fadeOut("normal");
popupStatus = 0; // and set value to 0
}
}
/************** end: functions. **************/
}); // jQuery End
私のvalidate.php:
<?PHP
// check that all POST variables have been set
if(!isset($_POST['method']) || !$method = $_POST['method']) exit;
if(!isset($_POST['value']) || !$value = $_POST['value']) exit;
if(!isset($_POST['target']) || !$target = $_POST['target']) exit;
$serverName = "localhost\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"MIQ", "UID"=>"sa", "PWD"=>"miq123");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$passed = false;
$retval = '';
switch($method)
{
case 'checkProduct':
$query = "SELECT PRODUCT_NAME, ESL, Product FROM ESL, SIQEE_IM_ITEM_INFORMATION WHERE ESL.Product = SIQEE_IM_ITEM_INFORMATION.GTIN AND SIQEE_IM_ITEM_INFORMATION.PRODUCT_NAME LIKE '%$value%'";
//Execute query
$qry_result = sqlsrv_query($conn, $query, array(), array("Scrollable"=>"buffered")) or die(sqlsrv_error());
//Build Result String
$display_string = '<table cellpadding="0" cellspacing="0" border="0" class="display" id="table_id" width="60%">';
$display_string .= "<thead>";
$display_string .= "<tr>";
$display_string .= "<th>ESL</th>";
$display_string .= "<th>Barcode</th>";
$display_string .= "<th>Product</th>";
$display_string .= "</tr>";
$display_string .= "</thead>";
$display_string .= "<tbody>";
// Insert a new row in the table for each person returned
while($row = sqlsrv_fetch_array($qry_result)){
$display_string .= "<tr id='row-clck' onmouseover='mouseover();'>";
$display_string .= "<td>$row[ESL]</td>";
$display_string .= "<td>$row[Product]</td>";
$display_string .= "<td>$row[PRODUCT_NAME]</td>";-
$display_string .= "</tr>";
}
$display_string .= "</tbody>";
$display_string .= "</table>";
$num_results = sqlsrv_num_rows($qry_result);
if ($num_results > 0){
$retval = $display_string;
$passed = true;
}
else{
$retval = "Dit product is nog niet gekoppeld";
$passed = false;
}
// ...
// set the $retval message, and the $passed variable to true or false
// ...
break;
case 'checkBarcode':
$query = "SELECT PRODUCT_NAME, ESL, Product FROM ESL, SIQEE_IM_ITEM_INFORMATION WHERE ESL.Product = '$value' AND SIQEE_IM_ITEM_INFORMATION.GTIN = '$value'";
//Execute query
$qry_result = sqlsrv_query($conn, $query, array(), array("Scrollable"=>"buffered")) or die(sqlsrv_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>ESL</th>";
$display_string .= "<th>Barcode</th>";
$display_string .= "<th>Product</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = sqlsrv_fetch_array($qry_result)){
$display_string .= "<tr>";
$display_string .= "<td>$row[ESL]</td>";
$display_string .= "<td>$row[Product]</td>";
$display_string .= "<td>$row[PRODUCT_NAME]</td>";-
$display_string .= "</tr>";
}
$display_string .= "</table>";
$num_results = sqlsrv_num_rows($qry_result);
if ($num_results > 0){
$retval = $display_string;
$passed = true;
}
else{
$retval = "Deze barcode is nog niet gekoppeld";
$passed = false;
}
// ...
// set the $retval message, and the $passed variable to true or false
// ...
break;
case 'checkAge':
if ($value >= 16 && $value <= 100){
$retval = "is helemaal goed";
$passed = true;
}
else{
$retval = "Nope no can do";
$passed = false;
}
// ...
// set the $retval message, and the $passed variable to true or false
// ...
break;
case 'checkEmail':
//build query
$query2 = "SELECT PRODUCT_NAME, ESL, Product FROM ESL, SIQEE_IM_ITEM_INFORMATION WHERE ESL.ESL = '$value' AND SIQEE_IM_ITEM_INFORMATION.GTIN = ESL.Product";
//Execute query
$qry_result2 = sqlsrv_query($conn, $query2, array(), array("Scrollable"=>"buffered")) or die(sqlsrv_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>ESL</th>";
$display_string .= "<th>Barcode</th>";
$display_string .= "<th>Product</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = sqlsrv_fetch_array($qry_result2)){
$display_string .= "<tr>";
$display_string .= "<td>$row[ESL]</td>";
$display_string .= "<td>$row[Product]</td>";
$display_string .= "<td>$row[PRODUCT_NAME]</td>";-
$display_string .= "</tr>";
}
$display_string .= "</table>";
$num_results2 = sqlsrv_num_rows($qry_result2);
if ($num_results2 > 0){
$retval = $display_string;
$passed = true;
}
else{
$retval = "Deze ESL is nog niet gekoppeld";
$passed = false;
}
// ...
// set the $retval message, and the $passed variable to true or false
// ...
break;
default: exit;
}
include "class.xmlresponse.php";
$xml = new xmlResponse();
$xml->start();
// set the response text
$xml->command('setcontent',
array('target' => "rsp_$target", 'content' => htmlentities($retval))
);
if($passed) {
// set the message colour to green and the checkbox to checked
$xml->command('setstyle',
array('target' => "rsp_$target", 'property' => 'color', 'value' => 'green')
);
$xml->command('setproperty',
array('target' => "valid_$target", 'property' => 'checked', 'value' => 'true')
);
} else {
// set the message colour to red, the checkbox to unchecked and focus back on the field
$xml->command('setstyle',
array('target' => "rsp_$target", 'property' => 'color', 'value' => 'red')
);
$xml->command('setproperty',
array('target' => "valid_$target", 'property' => 'checked', 'value' => 'false')
);
$xml->command('focus', array('target' => $target));
}
$xml->end();
?>