使用 ajax 将 id 元素传递给数据库


Passing id element to database using ajax

我有以下代码,可以工作:

<script>
function showUser(str) {
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>
<body>
<?php include 'db_connector.php';
$result = mysqli_query($con,"SELECT * FROM scope");
while($row = mysqli_fetch_array($result)) {
$row['name'];
echo  "<div class='toggle-btn-grp cssonly'>
<div><input type='radio' name='os' value=".$row['name']." id='myRadio' onchange='showUser(this.value)'>      <label  class='toggle-btn'>".$row['name']."</label></div>
</div>";
            }

 ?>
 <p>Click the "Try it" button to display the value of the radio button.</p>
 <button onclick="myFunction()">Try it</button>
 <div id="txtHint"></div>
 </body>

现在我想重复相同的过程,使用另一个单选按钮,但这次我希望新单选按钮的值是用户从<div id="txtHint"></div>中选择的值。

这可能吗??

这是我的后端getuser.php文件:

<?php
$q = strval($_GET['q']);
echo "<center><b>Scope ".$q."</b></center><br><br>";
include 'db_connector.php';
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM os WHERE scope = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {  
echo "<a href=''>ID: ".$row['id']."</a><br>";
echo "<a href=''>Name: ".$row['name']."</a><br><br>";
}
mysqli_close($con);

?>

任何建议将不胜感激。提前谢谢。

你应该看看这个答案。

StackOverflow答案:在浏览器中获取选定的文本,跨平台

根据

您编写的内容,我猜您想根据用户从 txtHintdiv 的内容中选择的文本创建一个新的单选按钮。

问题在于,无论你使用普通的javascript,都可能很难以跨浏览器的方式完成。

也许你正在学习javascript,尝试使用jQuery,特别是针对AJAX...真棒!

以下答案还建议使用 jQuery 插件和以跨浏览器支持的方式完成的 wrapSelect 插件!