简体   繁体   English

使用JavaScript函数中传递的变量

[英]Use a variable passed in a JavaScript function

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 非常感谢

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) {

You need to understand about javascript string c​oncatenation 您需要了解有关javascript字符串连接的信息

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 + '"';

I don't see how this will ever send your SQL query to your database. 我看不到它将如何将您的SQL查询发送到您的数据库。 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). 如果只是将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. 根据您尝试如何在select框中的选项更改时触发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. 这会将所有onchange事件发送到getCities.php文件,您可以在其中$_POST['countryID']检索countryID ,然后将其插入到SQL查询中,检索结果集,然后打印出选择字段的选项。 jQuery would then set the options of the select field to the result of the PHP script. 然后,jQuery将select字段的选项设置为PHP脚本的结果。

Also, it would be worth considering using Postgres prepared statements when querying your database to improve security. 同样,在查询数据库以提高安全性时值得考虑使用Postgres 准备的语句

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM