如何在javascript标签中编写php代码

koe*_*koe 0 html javascript php jquery

我有这样的代码

<select onchange="getval(this);"> 
     <option value="">Select</option>
     <option value="1">one</option>
     <option value="2">two</option>
     <option value="3">three</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我的剧本就像这样

function getval(sel){
//alert(sel.value);
    <?php $sql = "SELECT * FROM tbl_table WHERE id="?>+(sel.value)
}
Run Code Online (Sandbox Code Playgroud)

我希望从表中选择数据,其中id值来自javascript,但我不知道如何在javascript标签中编写php以及如何(sel.value)在PHP之后添加javascript的变量

我该如何纠正这种语法?

小智 5

愿这对你有所帮助.你可以使用ajax ......

mainfile.php中

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>

function getval(x){
    var data_arr="id="+x;  
    $.ajax({
        type:"POST",
        url:"anotherfile.php",
        data:data_arr,
         success: function(response){
            // here your response will come now you have to deside how to maintain this response...
         }

    });
}
</script>

<select onchange="getval(this.value);"> 
     <option value="">Select</option>
     <option value="1">one</option>
     <option value="2">two</option>
     <option value="3">three</option>
</select>
Run Code Online (Sandbox Code Playgroud)

你的另一个包含ajax代码的文件在这里......

anotherfile.php

<?php 
mysql_connect("hostname","username","password");
mysql_select_db("database_name");
$sql = "SELECT * FROM tbl_table WHERE id=".$_REQUEST['id'];
while($row = mysql_fetch_array($sql)){
    // here your out put data code...
}
// and finally write all data in echo statement they will return as response
Run Code Online (Sandbox Code Playgroud)

希望你明白了......