使用JavaScript函数中传递的变量

时间:2021-09-18 12:33:11

I have a select with all my countries and I call to a function onChange to get the list of cities for that country as per the code below:

我有一个选择我所有的国家,我打电话给一个函数onChange得到该国家的城市列表,按照下面的代码:

<select name="country" id="country" onChange="getCity(this.value)">

and I have the code to get the list of cities from my database as per code below:

我有代码从我的数据库中获取城市列表,如下面的代码:

<script language="javascript" type="text/javascript">
function getCity() {
    $(function(countryId) {
         var str = '<select name="city" id="city"><?php $query = "SELECT city FROM cities where country = 'countryId'";

    $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>';  
        document.getElementById('citydiv').innerHTML= str;
    });
}
</script>

How can I pass the variable countryId?

如何传递变量countryId?

If I use the following trying to use the variable countryId my code is not working.

如果我使用以下尝试使用变量countryId我的代码不起作用。

var str = '<select name="city" id="city">
<?php $query = "SELECT city FROM cities where country = 'countryId'";

However, if I change the value and introduce a particular value manually then it works:

但是,如果我更改值并手动引入特定值,那么它的工作原理如下:

var str = '<select name="city" id="city">
<?php $query = "SELECT city FROM cities where country = 'Albania'";

Please notice that my var str is storing all the following code to write up the city Div as it goes:

请注意我的var str存储了以下所有代码来编写城市Div:

var str = '

var str ='

var str = '<select name="city" id="city"><?php $query = "SELECT city FROM cities where country = 'Spain'"; 
    $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>';  

UPDATE

Based on the answers, I'm looking to accomplish something like

根据答案,我希望完成类似的事情

<script language="javascript" type="text/javascript">
function Nadaquever(countryId) {
    $(function() {
         var str = '<select name="city" id="city"><?php $query = "SELECT city FROM cities where country = ' + countryID + '"';          
         str += '$result = pg_query($query);';
         str += 'if (!$result) {';
         str += 'echo "Problem with query " . $query . "<br/>";';
         str += 'echo pg_last_error();';
         str += 'exit();';
         str += '}';
         str += 'printf ("<option value=Select>Select a City</option>");';
         str += 'while($myrow = pg_fetch_assoc($result)) {';
         str += 'printf ("<option value=$myrow[city]>$myrow[city]</option>");';
         str += '}?></select>';

document.getElementById('citydiv').innerHTML= str;
    });
}
</script>

But it is not working

但它没有用

Thank you so much

非常感谢

3 个解决方案

#1


0  

To apend a variable in Javascript you have to use + sign see the code below.

要在Javascript中添加变量,您必须使用+符号,请参阅下面的代码。

var str = 'blah blah blah';
str += ' blah';
str += ' ' + 'and some more blah';

also you need to pass the country id like this

你也需要像这样传递国家ID

function getCity(countryId) {

#2


0  

You need to understand about javascript string c​oncatenation

你需要了解javascript string c oncatenation

It has to change like below code.

它必须像下面的代码一样改变。

[right code]

var countryId = "myId";
var str = '<select name="city" id="city"><?php $query = "SELECT city FROM cities where country = ' + countryId + '"';

#3


0  

I don't see how this will ever send your SQL query to your database. If you are just concatenating Javascript strings together you will end up with just that - a string that contains some PHP tags which never sees the server (try logging the str var you have to the console and see what you have).

我不知道这将如何将您的SQL查询发送到您的数据库。如果你只是将Javascript字符串连接在一起,那么你最终会得到一个 - 一个包含一些永远不会看到服务器的PHP标记的字符串(尝试将你拥有的str var记录到控制台并看看你有什么)。

You'll need to think about the flow of your application. Based on how you are trying to get your Javascript function getCity() to fire when the option in the select box changes I assume you don't want to reload the page therefore you would need to send your SQL query to your database via AJAX.

您需要考虑应用程序的流程。根据您在选择框中的选项更改时尝试启动Javascript函数getCity()的方式,我假设您不想重新加载页面,因此您需要通过AJAX将SQL查询发送到数据库。

So assuming your markup looks like this:

所以假设你的标记看起来像这样:

<div id="citydiv">
  <select id="country" name="countryID">
    <option value="Select">Select a Country</option>
    <option value="Albania">Albania</option>
  </select>
  <select id="city" name="city">
    <option value="Select">Select a City</option>
  </select>
</div> 

You could use jQuery to generate the options for the city field like so:

您可以使用jQuery为city字段生成选项,如下所示:

$(function(){
  $('#country').on('change',function(){
    $.ajax({
      url: '/getCities.php',
      method: "POST",
      data: {countryID: $('#country').val() }
    })
    .done(function(data){
      $('#city').html(data);
    });
  });
});

This would send any onchange events to the getCities.php file where you can retrieve the countryID from $_POST['countryID'] and then insert this into your SQL query, retrieve the resultset and then print out the options for the select field. jQuery would then set the options of the select field to the result of the PHP script.

这会将任何onchange事件发送到getCities.php文件,您可以从$ _POST ['countryID']中检索countryID,然后将其插入到SQL查询中,检索结果集,然后打印出select字段的选项。然后,jQuery会将select字段的选项设置为PHP脚本的结果。

Also, it would be worth considering using Postgres prepared statements when querying your database to improve security.

此外,在查询数据库以提高安全性时,应该考虑使用Postgres准备好的语句。

#1


0  

To apend a variable in Javascript you have to use + sign see the code below.

要在Javascript中添加变量,您必须使用+符号,请参阅下面的代码。

var str = 'blah blah blah';
str += ' blah';
str += ' ' + 'and some more blah';

also you need to pass the country id like this

你也需要像这样传递国家ID

function getCity(countryId) {

#2


0  

You need to understand about javascript string c​oncatenation

你需要了解javascript string c oncatenation

It has to change like below code.

它必须像下面的代码一样改变。

[right code]

var countryId = "myId";
var str = '<select name="city" id="city"><?php $query = "SELECT city FROM cities where country = ' + countryId + '"';

#3


0  

I don't see how this will ever send your SQL query to your database. If you are just concatenating Javascript strings together you will end up with just that - a string that contains some PHP tags which never sees the server (try logging the str var you have to the console and see what you have).

我不知道这将如何将您的SQL查询发送到您的数据库。如果你只是将Javascript字符串连接在一起,那么你最终会得到一个 - 一个包含一些永远不会看到服务器的PHP标记的字符串(尝试将你拥有的str var记录到控制台并看看你有什么)。

You'll need to think about the flow of your application. Based on how you are trying to get your Javascript function getCity() to fire when the option in the select box changes I assume you don't want to reload the page therefore you would need to send your SQL query to your database via AJAX.

您需要考虑应用程序的流程。根据您在选择框中的选项更改时尝试启动Javascript函数getCity()的方式,我假设您不想重新加载页面,因此您需要通过AJAX将SQL查询发送到数据库。

So assuming your markup looks like this:

所以假设你的标记看起来像这样:

<div id="citydiv">
  <select id="country" name="countryID">
    <option value="Select">Select a Country</option>
    <option value="Albania">Albania</option>
  </select>
  <select id="city" name="city">
    <option value="Select">Select a City</option>
  </select>
</div> 

You could use jQuery to generate the options for the city field like so:

您可以使用jQuery为city字段生成选项,如下所示:

$(function(){
  $('#country').on('change',function(){
    $.ajax({
      url: '/getCities.php',
      method: "POST",
      data: {countryID: $('#country').val() }
    })
    .done(function(data){
      $('#city').html(data);
    });
  });
});

This would send any onchange events to the getCities.php file where you can retrieve the countryID from $_POST['countryID'] and then insert this into your SQL query, retrieve the resultset and then print out the options for the select field. jQuery would then set the options of the select field to the result of the PHP script.

这会将任何onchange事件发送到getCities.php文件,您可以从$ _POST ['countryID']中检索countryID,然后将其插入到SQL查询中,检索结果集,然后打印出select字段的选项。然后,jQuery会将select字段的选项设置为PHP脚本的结果。

Also, it would be worth considering using Postgres prepared statements when querying your database to improve security.

此外,在查询数据库以提高安全性时,应该考虑使用Postgres准备好的语句。