간단한 체인으로 연결된 선택 메뉴의 다음 예는 목표를 달성하는 방법에 대한 아이디어를 제공해야합니다.이를 연구하고 데이터베이스 호출을 구현해야하지만 전체 코드를 복사하고 당신이 당신의 자신의 데이터베이스 코드와 AJAX 위의 솔루션을 구현하려고 시도 할 수 없거나 꺼려하는 이유
<?php
/*
Include other PHP files/libraries,
set the session etc etc
.....
*/
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['action'], $_POST['id']) && $_POST['action']=='get_dependant_menu'){
ob_clean();
$action=filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING);
$id=filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
if($action && $id && !is_nan($id)){
/*
In production you would use the supplied POST values to query the database
and process the recordset - sending back the results as formatted HTML to
the AJAX callback function.
For the sake of demonstration though the script simply sends back data from a
simple loop...
sql=select * from table where id=? etc
*/
for($i=1; $i <= 10; $i++)echo "<option value='Service-$id-$i'>Service-$id-$i";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>Dependent/Chained SELECT menus</title>
<script type='text/javascript' charset='utf-8'>
/* Basic Ajax function */
function ajax(m,u,p,c,o){
/*
m=Method,
u=Url,
p=Params,
c=Callback,
o=Options
*/
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200)c.call(this, xhr.response, o, xhr.getAllResponseHeaders());
};
var params=[];
for(var n in p)params.push(n+'='+p[n]);
switch(m.toLowerCase()){
case 'post': p=params.join('&'); break;
case 'get': u+='?'+params.join('&'); p=null; break;
}
xhr.open(m.toUpperCase(), u, true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(p);
}
/* Callback function to populate second menu */
function createmenu(r,o,h){
/*
r=response
o=options (sent by ajax function)
h=response headers
*/
o.menu.innerHTML=r;
}
function bindEvents(){
/* Get references to the two dropdown menus */
var oSelItem=document.querySelector('select[name="item1"]');
var oSelService=document.querySelector('select[name="service1"]');
/* Assign an `onchange` event listener */
oSelItem.onchange=function(e){
var method='post';
var url=location.href;
/* the parameters to send to the PHP script */
var params={
'action':'get_dependant_menu',
'id':this.options[ this.options.selectedIndex ].value
};
/* Options to pass to the ajax callback */
var opts={
menu:oSelService
};
/* make the ajax request */
ajax.call(this, method, url, params, createmenu, opts);
}.bind(oSelItem);
}
document.addEventListener('DOMContentLoaded', bindEvents,false);
</script>
<style type='text/css' charset='utf-8'>
select {padding:1rem;width:300px;}
</style>
</head>
<body>
<h1>Chained select menus using basic ajax</h1>
<form method='post'>
<select name='item1' class='country'>
<?php
/*
In production your code would use a database call
to populate the menu but for example purposes it
simply uses a loop
*/
for($i=1; $i <= 10; $i++)echo "<option value=$i>Item $i";
?>
</select>
<select name='service1' class='country'>
</select>
</form>
</body>
</html>
는 모르겠지만 당신들이 지속적인 아마도 탄원 후 다음은 당신에게 더 나은 아이디어를 줄 것이다. 이것은 테스트되지 않았습니다! 새로운 행이 새로 추가 된 메뉴를 선택 클로닝되지 onchange를 이벤트 핸들러가 함수 bindEvents
상기 registed Add Row
버튼을 사용하여 추가
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['action'], $_POST['id']) && $_POST['action']=='get_dependant_menu'){
ob_clean();
$action=filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING);
$id=filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING);
if($action && $id && !empty($id)){
$sql='select * from service where irn = :irn order by sr asc';
$stmt->bindParam(':irn',$id);
$stmt->execute();
if($stmt->rowCount() > 0){
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
echo "<option value='{$row['IRN']}'>{$row['Name']}";
}
}
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>Dependent/Chained SELECT menus</title>
<script type='text/javascript' charset='utf-8'>
function ajax(m,u,p,c,o){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200)c.call(this, xhr.response, o, xhr.getAllResponseHeaders());
};
var params=[];
for(var n in p)params.push(n+'='+p[n]);
switch(m.toLowerCase()){
case 'post': p=params.join('&'); break;
case 'get': u+='?'+params.join('&'); p=null; break;
}
xhr.open(m.toUpperCase(), u, true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(p);
}
function createmenu(r,o,h){
o.menu.innerHTML=r;
}
function bindEvents(){
var oSelItem=document.querySelector('select[name="item1"]');
var oSelService=document.querySelector('select[name="service1"]');
oSelItem.onchange=function(e){
var method='post';
var url=location.href;
var params={
'action':'get_dependant_menu',
'id':this.options[ this.options.selectedIndex ].value
};
var opts={
menu:oSelService
};
ajax.call(this, method, url, params, createmenu, opts);
}.bind(oSelItem);
}
document.addEventListener('DOMContentLoaded', bindEvents,false);
</script>
<style type='text/css' charset='utf-8'>
select {padding:1rem;width:300px;}
</style>
</head>
<body>
<h1>Chained select menus using basic ajax</h1>
<form method='post'>
<select name='item1' class='country'>
<?php
$sql='select * from `item` order by `sr` asc;';
$stmt=$user_home->runQuery($sql);
$stmt->execute();
if($stmt->rowCount() > 0){
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
echo "<option value='{$row['IRN']}'>{$row['Name']}";
}
}
?>
</select>
<select name='service1' class='country'>
</select>
</form>
</body>
</html>
. & 새로 추가 된 모든 선택 메뉴가 동일한 메커니즘 (예 : 아약스)을 사용하려면 가장 쉬운 방법은 inline event handlers
을 item
드롭 다운 메뉴에 지정하는 것입니다. 자바 스크립트는 위의 (안 BTW 테스트)
<script type='text/javascript' charset='utf-8'>
/* AJAX FUNCTION */
function ajax(m,u,p,c,o){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200)c.call(this, xhr.response, o, xhr.getAllResponseHeaders());
};
var params=[];
for(var n in p)params.push(n+'='+p[n]);
switch(m.toLowerCase()){
case 'post': p=params.join('&'); break;
case 'get': u+='?'+params.join('&'); p=null; break;
}
xhr.open(m.toUpperCase(), u, true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(p);
}
/* AJAX CALLBACK */
function createmenu(r,o,h){
o.menu.innerHTML=r;
}
/* INLINE EVENT HANDLER */
function evtselect(e){
try{
var el=e.target;
/* it is NOT necessary to have the `action` parameter... that was for testing for me initially */
var params={
'action':'get_dependant_menu',
'id':el.value
};
/*
newly added nodes (add row) should have their names changed*/
so the following line needs attention! Basically you need to find, in the DOM,
the next select menu on the same row (think parentNode, nextSibling etc etc)
The following is NOT tested......!!!!!
*/
var td=el.parentNode.nextSibling;
var opts={
menu:td.querySelector('select')
};
ajax.call(this, method, url, params, createmenu, opts);
}catch(err){
console.log(err);
}
}
</script>
사용하려면 변경 될 수 inline event handler
당신이 일반적으로 할 것 :
<select name='item' onchange='evtselect(event)'>/* options */</select>
나는 당신의 필요를 이해한다면, 당신은 완전히 다른 방법을 사용해야합니다. 가능한 해결책 : 1) 첫 번째 Items 쿼리는 해당 '
@cFreed Ok, 그렇게하는 법? 내 코드를 추가/편집하여 설명해 주시겠습니까? – BTC