如何获取变量选择/选择下拉菜单PHP或HTML的值 [英] How to get in a variable the value of the selection of a Select/Drop Down Menu PHP or HTML

查看:227
本文介绍了如何获取变量选择/选择下拉菜单PHP或HTML的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连接2个下拉菜单,所以首先我会显示一个国家列表,并根据选择的国家,显示所选国家的城市列表。



我有我的index.php文件正确载入所有国家/地区,如图所示:





加载我的国家/地区的代码

  select name =countryid =country> 
<?php
$ db = pg_connect($ db_host $ db_name $ db_username $ db_password);
$ query =SELECT country FROM countries;

$ result = pg_query($ query);
if(!$ result){
echo查询问题。 $查询。 <峰; br /> 中;
echo pg_last_error();
exit();
}

printf(< option value = Select>选择国家< / option>);
while($ myrow = pg_fetch_assoc($ result)){
printf(< option value = $ myrow [country]> $ myrow [country]< / option>);
}
?>
< / select>

现在我根据之前的选择选择做同样的事情,但是不管用。我遇到的问题是获得在国家/地区选择的值,因为如果我硬键输入一个国家的值,如:$ query =SELECT city FROM cities where country = Albania;那么它工作。另外我试图打印所选国家的值:(echo $ selectedCountry;),它不打印任何东西,所以我猜两个$ selectedCountry = $ _GET ['country'];或$ selectedCountry = $ _POST ['country'];正在获取所选国家的价值。

 < select name =cityid =city> 
<?php
$ db = pg_connect($ db_host $ db_name $ db_username $ db_password);

$ selectedCountry = $ _GET ['country'];
$ selectedCountry = $ _POST ['country'];
echo $ selectedCountry;

$ query =SELECT city FROM cities where country ='$ selectedCountry';

$ result = pg_query($ query);
if(!$ result){
echo查询问题。 $查询。 <峰; br /> 中;
echo pg_last_error();
exit();
}
printf(< option value = Select>选择城市< / option>);
while($ myrow = pg_fetch_assoc($ result)){
printf(< option value = $ myrow [city]> $ myrow [city]< / option>);
}
?>
< / select>

提前非常感谢你



更新



这是我在第一次加载中看到的。国家/地区选择按照上述图像加载所有值,城市选择为空(仅选择城市值)等待根据国家/地区选择加载值。





最近更新 - 从博尔纳建议



Borna,



我已经尝试过您的建议, '使用。以两个国家为例。然而,城市是空的第一次加载,当我选择一个国家没有加载在城市选择,我得到以下屏幕。它接缝实际上不是调用/运行getCities.php:





Index.html

 <!DOCTYPE html> 
< html>
< head>

< script>
函数populateCities(citiesSelectBoxOptions){
document.getElementById(city)innerHTML = citiesSelectBoxOptions;
}

函数httpGetAsync(theUrl,callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4&& xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open(GET,theUrl,true); // true for asynchronous
xmlHttp.send(null);
}
< / script>
< / head>
< body>

< select name =countryid =countryonchange =httpGetAsync('http:// localhost / FillCity / getCities?country ='+ this.value,populateCities)>
< option value =安哥拉>安哥拉< / option>
< option value =Spain>西班牙< / option>
< / select>

< select name =cityid =city>

< / select>

< / body>
< / html>

getCities.php

 <?php 

include(config.php);

$ db = pg_connect($ db_host $ db_name $ db_username $ db_password);
$ selectedCountry = $ _GET ['country'];
echocountry:。$ country;

$ query =SELECT city FROM cities where country ='$ selectedCountry';

$ result = pg_query($ query);
if(!$ result){
echo查询问题。 $查询。 <峰; br /> 中;
echo pg_last_error();
exit();
}
printf(< option value ='Select'>选择城市< / option>);
while($ myrow = pg_fetch_assoc($ result)){
printf(< option value ='$ myrow [city]'> $ myrow [city]< / option>);
}
?>

更新



如果我运行



如果我只运行< a href =http://localhost/FillCity/getCities.php =nofollow noreferrer> http://localhost/FillCity/getCities.php 我得到:(我得到这个词,因为我在代码中放置并回覆$ country,以查看所选的国家)





这是我的localhost下的FillCity文件夹(var / www / html)





这里是我第一次使用安哥拉作为默认国家/地区运行Index.html时看到的。





如果我选择任何国家/地区,西班牙,例如这是我得到的





最近更新



当我打开.html文件,我选择一个国家这是我得到的(仍然在屏幕上打印出这个消息):





一旦我点击Ok,它的工作,我可以看到所有的城市的国家(但当然我不想让消息弹出)





谢谢再次

解决方案

嗯,您真正需要的是AJAX调用,它允许您与服务器通信而不重新加载页面。所有你需要做的是基本上发送一个新的HTTP请求与国家参数,以获得其中的城市列表。正确的方法是发送(HTTP响应)只有JSON或类似格式的数据(城市),而不是它的演示文稿(html),但为了简单起见,您可以像开始(使用html返回数据)继续工作, 。



首先分开生成另一个脚本中城市的HTML selectBoxOptions的代码。
您将使用该脚本通过使用AJAX(XMLHttpRequest库)获取特定国家/地区的城市列表。



看看这个,这是一个工作解决你的问题。当用户更改countrySelectBox选项时,会发送HTTP请求,这样您的城市选择框将在每次需要时更新。
所有你需要做的是更改指向你的脚本的onchange属性中的url(我以前说你应该将第二个代码块移动到单独的脚本中)。

 <!DOCTYPE html> 
< html>
< head>

< script>
函数populateCities(citiesSelectBoxOptions){
document.getElementById(city)innerHTML = citiesSelectBoxOptions;
}

函数httpGetAsync(theUrl,callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4&& xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open(GET,theUrl,true); // true for asynchronous
xmlHttp.send(null);
}
< / script>
< / head>
< body>


< select name =countryid =countryonchange =httpGetAsync('www.yourdomain.com/getCities.php?country='+ this.options [this .selectedIndex] .value,populateCities)>
< option value =Country1>国家1< / option>
< option value =Country2>国家2< / option>
< / select>

< select name =cityid =city>

< / select>

< / body>
< / html>

getCities.php

 <?php 

$ db = pg_connect($ db_host $ db_name $ db_username $ db_password);

$ selectedCountry = $ _GET ['country'];

$ query =SELECT city FROM cities where country ='$ selectedCountry';

$ result = pg_query($ query);
if(!$ result){
echo查询问题。 $查询。 <峰; br /> 中;
echo pg_last_error();
exit();
}
printf(< option value ='Select'>选择城市< / option>);
while($ myrow = pg_fetch_assoc($ result)){
printf(< option value ='$ myrow [city]'> $ myrow [city]< / option>);
}
?>

编辑:



httpGetAsync是native只使用纯/ vanilla javascript,没有其​​他库)javascript函数,使您能够发送HTTP请求而不重新加载页面。我看到你正在使用jQuery,它隐藏了这个功能的复杂性,与form-> submit相同,但是我建议您了解httpGetAsync的工作原理,因为对于这样一个简单的任务使用jQuery是非常有用的。



您不需要此JavaScript功能

  function getCity(countryId)

相反,您应该将与数据库通信的代码放在.php文件中,而不是javascript(记住,javascript是客户端在客户端机器上执行,例如浏览器,而php在服务器上执行)。你的SQL不应该写在javascript中。客户端代码不能直接与数据库通信,只能通过服务器端编码。要实现这一点,您必须将PHP脚本getCities.php的值作为HTTP响应返回给客户端(javascript)。



向一些HTTP请求发送HTTP请求.php文件,这些脚本在服务器上执行,并且脚本末尾所说的echo或print的所有内容都将自动发送为HTTP响应。你不需要写任何代码来发送HTTP响应。它自动完成你只需要在客户端回传/打印任何你需要的东西。在您的情况下,您需要打印特定国家/地区的选项。



脚本如何知道从数据库中选择城市所需的国家?
那么你发送一个参数country的HTTP请求。那就是你在提交表单时自动执行的操作。 Form中的所有HTML标签和设置了name属性的HTML标签将作为参数发送在HTTP请求中。但是,由于您不能使用提交,您必须手动执行此操作。



要在HTTP GET请求内发送参数非常简单。
看看以下url:

  localhost / getCities?country = countryX& someOtherParam = something& myThirdParam = something3 

在服务器端,以下变量将被填充:

  $ _ GET [country] // value is'countryX'
$ _GET [someOtherParam] // value is'something'
$ _GET [myThirdParam] // value is'something3'

要了解更多关于如何GET和POST工作,有什么区别,请查看



通过创建一个getCities.php文件开始,并复制粘贴与数据库通信的代码,并生成城市选项。这基本上是你已经做过的,你只需要将该代码放在单独的.php文件中。因此,当客户端(浏览器)要求特定国家/地区的城市列表时,您将发送HTTP请求(使用httpGetAsync()函数)从服务器获取该列表。



在你的index.php中复制粘贴这个脚本

 < script> 
函数populateCities(citiesSelectBoxOptions){
document.getElementById(city)innerHTML = citiesSelectBoxOptions;
}

函数httpGetAsync(theUrl,callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4&& xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open(GET,theUrl,true); // true for asynchronous
xmlHttp.send(null);
}
< / script>

接下来,在选择框上放置onchange属性,记住它的小写,而不是onChange。 p>

 < select name =countryid =countryonchange =httpGetAsync('localhost / getCities?country ='+ this .value,populateCities)> 

任何问题只要问...:)


I'm trying to connect 2 drop-downs so in the first I show a list of countries and based on the selection of the country I show a list of the cities for the country selected.

I have my index.php file which load all the countries correctly as seen in this image:

Code to load my countries

<select name="country" id="country">
    <?php
    $db = pg_connect("$db_host $db_name $db_username $db_password");
    $query = "SELECT country FROM countries";

    $result = pg_query($query);
    if (!$result) {
        echo "Problem with query " . $query . "<br/>";
        echo pg_last_error();
        exit();
    }

    printf ("<option value=Select>Select a Country</option>");
    while($myrow = pg_fetch_assoc($result)) {
    printf ("<option value=$myrow[country]>$myrow[country]</option>");
 }
    ?>
</select>

Now I'm trying to do the same based on the selection from the previous "Select" but it is not working. The issue I'm having is getting the value selected in the country select because if I hard-type a value of a country like: $query = "SELECT city FROM cities where country = Albania"; then it works. Also I tried to print the value of the country selected: (echo $selectedCountry;) and it not printing anything so I'm guessing neither $selectedCountry = $_GET['country']; or $selectedCountry = $_POST['country']; are getting the value of the country selected.

<select name="city" id="city">
    <?php
    $db = pg_connect("$db_host $db_name $db_username $db_password");

$selectedCountry = $_GET['country'];
    $selectedCountry = $_POST['country'];
    echo $selectedCountry;

    $query = "SELECT city FROM cities where country = ' $selectedCountry '";

    $result = pg_query($query);
    if (!$result) {
        echo "Problem with query " . $query . "<br/>";
        echo pg_last_error();
        exit();
    }
    printf ("<option value=Select>Select a City</option>");
    while($myrow = pg_fetch_assoc($result)) {
    printf ("<option value=$myrow[city]>$myrow[city]</option>");
}
    ?>
</select>

Thank you very much in advance

UPDATE

This is what I see in the first Load. Where the country Select is loaded with all the values as per the image above and the city Select is empty (Only the "Select a city" value) waiting to be loaded with the values depending on the country selection.

LAST UPDATE - From Borna Suggestion

Borna,

I've tried your suggestion, below the exact code that I'm using. Using two countries as example. However, the cities are empty the first load and when I select a country nothing loads in the city Select and I get the following screen. It seams that it is actually not calling/running the getCities.php:

Index.html

<!DOCTYPE html>
<html>
<head>

<script>
    function populateCities(citiesSelectBoxOptions){
        document.getElementById("city").innerHTML = citiesSelectBoxOptions;
    }

    function httpGetAsync(theUrl, callback)
    {
        alert(theUrl);
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                callback(xmlHttp.responseText);
        }
        xmlHttp.open("GET", theUrl, true); // true for asynchronous
        xmlHttp.send(null);
    }
</script>
</head>
<body>

<select name="country" id="country" onchange="httpGetAsync('http://localhost/FillCity/getCities?country=' + this.value, populateCities)">
<option value="Angola">Angola</option>
<option value="Spain">Spain</option>
</select>

<select name="city" id="city">

</select>

</body>
</html>

getCities.php

<?php

include("config.php");

$db = pg_connect("$db_host $db_name $db_username $db_password");
$selectedCountry = $_GET['country'];
echo "country: " .$country;

$query = "SELECT city FROM cities where country = ' $selectedCountry '";

$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value='Select'>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value='$myrow[city]'>$myrow[city]</option>");
}
?>

UPDATE

If I run http://localhost/FillCity/getCities?country=Spain this is what I get

If I run just http://localhost/FillCity/getCities.php I get: (I'm getting the word country because I place and echo $country in the code to see the country selected)

This is my FillCity folder under my localhost (var/www/html)

And here is what I see when running the Index.html for the first time with Angola as default country.

If I select any country, Spain, as example this is what I get

LAST UPDATE

When I open the .html file and I select a country this is what I get (Still printing out that message on the screen):

Once I click Ok then it works and I can see all the cities for the country (But of course I would like not to have that message popping up)

Thanks again

解决方案

Well, what you really need is AJAX call which allows you to communicate with server without reloading a page. All you have to do is basically send a new HTTP request with a country parameter to get the list of cities in it. The correct way would be to send (HTTP response) only the data(cities) in JSON or similar format, and not its presentation also (html), but for simplicity, you can continue to work like you started (return data with html).

Start by separating the code that generates HTML selectBoxOptions of cities in another script. You will use that script to get the list of cities in particular country by using AJAX (XMLHttpRequest library).

Have a look at this, it's a working solution of your problem. HTTP request is sent whenever user changes the countrySelectBox option, that way your cities select box gets updated every time it needs. All you have to do is change the url in the onchange attribute that points to your script (I previously said that you should move 2nd block of code into separate script).

<!DOCTYPE html>
<html>
<head>

    <script>
        function populateCities(citiesSelectBoxOptions){
            document.getElementById("city").innerHTML = citiesSelectBoxOptions;
        }

        function httpGetAsync(theUrl, callback)
        {
            alert(theUrl);
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                    callback(xmlHttp.responseText);
            }
            xmlHttp.open("GET", theUrl, true); // true for asynchronous
            xmlHttp.send(null);
        }
    </script>
</head>
<body>


<select name="country" id="country" onchange="httpGetAsync('www.yourdomain.com/getCities.php?country=' + this.options[this.selectedIndex].value, populateCities)">
    <option value="Country1">Country 1</option>
    <option value="Country2">Country 2</option>
</select>

<select name="city" id="city">

</select>

</body>
</html>

getCities.php

<?php

$db = pg_connect("$db_host $db_name $db_username $db_password");

$selectedCountry = $_GET['country'];

$query = "SELECT city FROM cities where country = ' $selectedCountry '";

$result = pg_query($query);
if (!$result) {
    echo "Problem with query " . $query . "<br/>";
    echo pg_last_error();
    exit();
}
printf ("<option value='Select'>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
    printf ("<option value='$myrow[city]'>$myrow[city]</option>");
}
?>

EDIT:

httpGetAsync is native (only pure/vanilla javascript is used. No other libraries are used) javascript function that enables you to send HTTP request without reloading a page. I see you are using jQuery, which hides this function's complexity, same as form->submit, but I recommend you to learn how httpGetAsync works, because using a jQuery for such a simple task is overkill.

You don't need this javascript function

function getCity(countryId) 

Instead, you should put your code that communicates with database in a .php file, not in javascript (remember, javascript is a client side, it executes on client machine, e.g. browser, while php executes on server). Your SQL should never be written in javascript. Client side code cannot communicate with a database directly, only through server side coding. To accomplish that, you must return a value of PHP script getCities.php back to the client(javascript) as a HTTP response.

When you send a HTTP request to some .php file, that scripts executes on a server, and everything that you said "echo" or "print", on the end of script, is automaticaly sent as HTTP response. You don't actualy have to write any code to send a HTTP response. Its done automaticaly. You just have to echo/print whatever you need on the client side. In your case, you need to print options for particular country.

How the script knows for which country it needs to select cities from database? Well, you send HTTP request with a parameter "country". That is what you Form is doing automaticaly when you submit it. All HTML tags that are inside Form, and have a name attribute set, are gonna be send in HTTP request as parameters. But, since you cannot use submit, you must do this manualy.

To send a parameter inside HTTP GET request is very simple. Have a look at the following url:

localhost/getCities?country=countryX&someOtherParam=something&myThirdParam=something3

On server side, the following variables are gonna be populated:

$_GET["country"] // value is 'countryX'
$_GET["someOtherParam"] // value is 'something'
$_GET["myThirdParam"] // value is 'something3'

To learn more about how GET and POST works, and what is the difference, check this

Get started by creating a getCities.php file, and copy paste the code that communicates with database and generates city options. It's basically what you already did, you just have to put that code in separate .php file. So, when a client (browser) asks for a list of cities in particular country, you are going to send a HTTP request (using httpGetAsync() function) to get that list from the server.

In your index.php copy paste this script

<script>
    function populateCities(citiesSelectBoxOptions){
        document.getElementById("city").innerHTML = citiesSelectBoxOptions;
    }

    function httpGetAsync(theUrl, callback)
    {
        alert(theUrl);
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                callback(xmlHttp.responseText);
        }
        xmlHttp.open("GET", theUrl, true); // true for asynchronous
        xmlHttp.send(null);
    }
</script>

Next, put onchange attribute on select box, remember, its all lower case, not onChange.

<select name="country" id="country" onchange="httpGetAsync('localhost/getCities?country=' + this.value, populateCities)">

For any question just ask... :)

这篇关于如何获取变量选择/选择下拉菜单PHP或HTML的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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