根据第一个选择选项更改第二个选择选项

时间:2017-08-06 08:31:25

标签: javascript php

我有两个php循环,一个有CPU选择选项,它还有socket var。第二个是主板选择选项的另一个php循环,它也有socket var。但是,如果您选择带有插座LGA1151的CPU并且主板有另一个不同的插座,我需要将第二个环(主板)更改为仅显示主机,其插座与所选的CPU相同。

这是我的2循环代码

        <li class="flip-container" style="z-index: 19;">
          <div class="flipper default">
            <div class="front">
              <h2>CPU</h2>
            </div>
            <div class="back" style="height:auto;width:400px;padding:15px; ">
              <script>
				function cpuPreview(sel) {
					document.getElementById('Imgcpu').src = "" + sel.options[sel.selectedIndex].id;
				}
				</script>
			    <div class="custom-select">
			    	<label for="select-choice1" class="label select-1"><span class="selection-choice">Please choose something</span> </label>
			    	<select id="cpu" name="cpu" class="select" onChange="cpuPreview(this)" >
				    	<option data-price="0">Please select 1</option>
				    	<?php $psut = $con->query("SELECT * FROM parts WHERE type = 'cpu'");?>
   						<?php while($psu = $psut->fetch_object()): ?>
			      		<option id="<?= $psu->image ?>" value="<?= $psu->id ?>" data-price="<?= $psu->price ?>"><?= $psu->name ?></option>
				  		<?php endwhile;?>
					</select>
			  	</div>
			  		<img id='Imgcpu' src="" width="300px" height="auto">
            </div>
          </div>
        </li>

        <li class="flip-container" style="z-index: 17;">
          <div class="flipper default">
            <div class="front">
              <h2>Motherboard</h2>
            </div>
            <div class="back" style="height:auto;width:400px;padding:15px; ">
              <script>
				function motherboardPreview(sel) {
					document.getElementById('Imgmotherboard').src = "" + sel.options[sel.selectedIndex].id;
				}
				</script>
			    <div class="custom-select">
			    	<label for="select-choice1" class="label select-1"><span class="selection-choice">Please choose something</span> </label>
			    	<select id="motherboard" name="motherboard" class="select" onChange="motherboardPreview(this)" >
				    	<option data-price="0">Please select 1</option>
				    	<?php $psut = $con->query("SELECT * FROM parts WHERE type = 'motherboard'");?>
   						<?php while($psu = $psut->fetch_object()): ?>
			      		<option value="<?= $psu->id ?>" id="<?= $psu->image ?>" data-price="<?= $psu->price ?>"><?= $psu->name ?></option>
				  		<?php endwhile;?>
					</select>
			  	</div>
			  		<img id='Imgmotherboard' src="" width="300px" height="auto">
            </div>
          </div>
        </li>      

1 个答案:

答案 0 :(得分:0)

作为一个粗略的指南,您可以使用ajax获得所需的结果,也许以下内容可能会有用。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['cpu'] ) ){
        ob_clean();

        $dbhost =   'localhost';
        $dbuser =   'xxx'; 
        $dbpwd  =   'xxx'; 
        $dbname =   'xxx';
        $con    =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );



        $cpu=filter_input( INPUT_POST, 'cpu', FILTER_SANITIZE_STRING );
        $type='motherboard';



        /* SQL is purely guesswork ~ */
        $sql='select `id`,`name` from `parts` where type=? and cpu=?';
        $stmt=$con->prepare( $sql );


        if( $stmt ){

            /* Bind parameters to the placeholders */
            $stmt->bind_param( 'ss', $type, $cpu );
            $result = $con->execute();


            if( $result ){

                /* if the query succeeded, iterate through stored results */
                $stmt->bind_result( $id, $name );

                /* set header */
                header('Content-Type: text/html' );

                while( $stmt->fetch() ){
                    /* echo HTML content back to ajax callback */
                    echo "<option value='$id'>$name";
                }
            }


            $stmt->free_result();
            $stmt->close();
            $con->close();
        }
        exit();
    }
?>
<!doctype html>
<html>
    <head>
        <title>ajax dependant select menu</title>
        <script>
            function getmotherboard(e){
                var xhr=new XMLHttpRequest();
                xhr.onload=function(e){
                    board.innerHTML=xhr.response;
                }
                xhr.onerror=function(e){
                    alert(e);
                }
                /* POST request to the same page or use url */
                xhr.open( 'POST', location.href, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( 'cpu='+this.value );
            }


            /* using `fetch` with CORS */
            /*
                In an attempt to get around the same-origin problem you 
                need to send a CORS request and the server needs to be setup
                to allow such requests. You can make the request using the
                now traditional ajax ( XMLHttpRequest ) or, in some ways easier,
                the new `fetch` api - though it is not fully supported by allow
                major browsers ( IE & safari notably I believe )
            */
            function fetchmotherboard(){
                var url=location.href;
                var board=document.querySelector('select[name="motherboard"]');

                /* Construct payload to send in request */
                var data=new FormData();
                    data.append( 'cpu', this.value );

                /* configuration for the request */
                var config={
                    method:'POST',
                    mode:'cors',
                    body:data,
                    credentials:'include'
                };

                /* success/fail callbacks */
                var evtCallback=function(r){
                    return r.text().then(function(text){
                        board.innerHTML=text;
                    });
                };
                var evtError=function(err){
                    console.log( err )
                };

                /* Create the request object */
                var request=new Request( url, config );

                /* Make the request */
                fetch( request ).then( evtCallback ).catch( evtError );
            }


            document.addEventListener('DOMContentLoaded',function(){
                var cpu=document.querySelector('select[name="cpu"]');
                var board=document.querySelector('select[name="motherboard"]');
                cpu.onchange=getmotherboard.bind( cpu );

                /* alt version using `fetch` */
                cpu.onchange=fetchmotherboard.bind( cpu );

            },false );
        </script>
    </head>
    <body>
        <form method='post'>

            <!-- content populated from db on page load -->
            <select name='cpu'>
                <option value='cpu_1'>cpu_1
                <option value='cpu_2'>cpu_2
                <option value='cpu_3'>cpu_3
            </select>

            <!-- content populated dynamically -->
            <select name='motherboard'></select>
        </form>
    </body>
</html>