如何从html选择选项onChange调用php函数? [英] How to call php function from html select option onChange?

查看:88
本文介绍了如何从html选择选项onChange调用php函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我整天都在为这个问题而苦苦挣扎,似乎无法解决它. 每当从下拉菜单中选择一个选项时,我都需要调用php查询.

So Ive been struggling with this problem all day and can't seem to get around it. I need to call a php query whenever an option from a dropdown menu is selected.

<select class="selectpicker" id="headSelector">
 <?php
  $cname = $_GET['cname'];

 $linkID = mysql_connect("localhost","USER","PASS");
 mysql_select_db("USR", $linkID);               

 $SQLCurr = "SELECT `AName` FROM `Char-Armor` WHERE `CName` = '$cname' AND `AType`= 'Head'";
 $currHeadValues = mysql_query($SQLCurr, $linkID);
 $currRow = mysql_fetch_row($currHeadValues);
 $curr = $currRow[0];
 if($curr == '' || $curr == NULL){
     $curr = 'None';
 }

 $SQLHead = "SELECT AName FROM  `Armor` WHERE AType = 'Head'";
 $allHeadValues = mysql_query($SQLHead, $linkID);
 echo "<option>".$curr."</option>";
 while($row = mysql_fetch_assoc($allHeadValues)){
     echo "
         <option>".$row['AName']."</option>
     ";
 }
 ?>
 </select>

php部分需要从选项中获取'AName'并将其用于插入表中.

The php part needs to take the 'AName' from the option and use it to insert into a table.

我已经阅读了很多有关AJAX的文章,但是我不太了解它应该如何工作.我认为这就像html-> js-> Ajax-> php

I have done a lot of reading about AJAX but I do not quite understand how it is supposed to work. I think it is like html -> js -> Ajax -> php

选择一个选项后,我需要它保持在同一页面上.

I need it to stay on the same page when an option is selected.

任何解释都很好,谢谢!

Any explanation would be great, thanks!

推荐答案

这是您可以做的.

1).选择一个选项后,立即运行一个jQuery onchange事件并获取所选选项的值.

1). As soon as an option is selected, run a jquery onchange event and get the value of the selected option.

2).现在,使用选定值的值运行ajax请求,并将此数据发布到后端php文件中.

2). Now, run an ajax request with the value of the selected value and post this data to a backend php file.

3).现在,在此后端php文件上,接收数据并进行处理(运行查询).

3). Now on this backend php file, receive data and process (run the query).

代码示例.

以这种方式更改您的option行.

Change your option line in this way.

<option value="$row['AName']">".$row['AName']."</option>

jQuery-Ajax

jQuery-Ajax

$("#headSelector").change(function(e){
//get the value of the selected index.
value = $(this).val();
//make an ajax request now
$.ajax({
url: 'yourPhpBackendScript.php',
type: 'POST',
data: {value: value},
success:function(response)
{
alert(response);
}
})
})

yourPhpBackendScript.php

//You can now receive the selected value as $_POST['value'];
//get the value now
$value = $_POST['value'];
//you can apply validations if you want.
//Now, run the query and send a response. Response can be a simple message like data submitted etc. So
runQueryHere

echo "inserted"; //response returned to ajax rquest

这篇关于如何从html选择选项onChange调用php函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆