dqtm8504 2013-12-12 06:47
浏览 64
已采纳

需要帮助来访问javascript中perl脚本返回的JSON哈希

Let me clearly tell you what i want to accomplish in the end: I have a Php script which populates a dropdownlist using MySql db connect. Here is the code for PHP:

Start of PHP file

    <!DOCTYPE html>
    <head>
    <script>
    </script>
    </head>
    <body>
    <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">

    <label><b>Location : </b></label>
    <select name="loc" id="location-dropdown">

    <?php
    $host="****"; // Host name
    $username="****"; // Mysql username
    $password="****"; // Mysql password
    $db_name="*****"; // Database name
    $tbl_name="****"; // Table name

    $myid="2";
    //$myid=$_GET["id"];
    mysql_connect("$host", "$username", "$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");  

    $data = mysql_query("SELECT * FROM $tbl_name WHERE id='$myid'") or die     (mysql_error());

    while($info = mysql_fetch_array( $data ))
    {
    $loc=$info['location'];
    echo "<option value = $loc>$loc</option>";
                                }
    $p=shell_exec("AS.pl $myid ");                
    ?>
    </select>


    <div id="iamdiv"></div>
    </form>
    </body>
    </html>

**End of PHP file**

The contents of AS.pl:

Start of perl

    #!/usr/bin/perl

    use DBI;
    use Data::Dumper;
    use JSON;


    $id = "$ARGV[0]";

    $dbh = DBI->connect('dbi:mysql:****','****','****')
     or die "Connection Error: $DBI::errstr
";
    $sql = "SELECT * FROM details WHERE id='$id'";
    $sth = $dbh->prepare($sql);
     $sth->execute
     or die "SQL Error: $DBI::errstr
";
    while (my @row=$sth->fetchrow_array)
    {
      push (@loci,$row[2]); ## @loci is an array of locations like america,africa etc
    }
    $sth->finish;

## I have another array @values which contains numbers so i will just print out  both the arrays for ur ref:

    for($i=0;$i<=$#values;$i++)
    {
     print "$loci[$i] :$values[$i]
";
    }

The outputs

Singapore :2300
Amsterdam :2300
Mumbai :2300
Gurgaon :2300

i have a hash which is encoded to JSON

my %hash; @hash{@loci} = @values; my $json_text = encode_json(\%hash);

**Hash output**
$VAR1 = {
          'Gurgaon' => '2300',
          'Singapore' => '2300',
          'Mumbai' => '2300',
          'Amsterdam' => '2300'
        };

JSON output print $json_text; {"Gurgaon":"2300","Singapore":"2300","Mumbai":"2300","Amsterdam":"2300"}

**End of perl**

So basically what i want to do is: 1)The returned JSON contains locations as keys and values as values.I need to compare if the location values on the location dropdown and Json location values are same then i need to return the corresponding JSON value in the div id="iamdiv". I would need to use the onchange event of the dropdown i guess,but how to use the json returned by perl here in javascript?

  • 写回答

1条回答 默认 最新

  • duanhe4267 2013-12-12 07:32
    关注

    First you need to move out $p=shell_exec("AS.pl $myid "); out of the select tag and place it inside a script tag.

    <script type="text/javascript">
     var jsonString = <?php shell_exec("AS.pl $myid ");?>
    </script>
    

    Then you must either ensure to run the javascript after all the DOM is loaded. Or simply you may put the javascript at the bottom of your page.

    <script type="text/javascript">
        var locInfo = eval("(" + jsonString + ")");// make a json object from string
        var select = document.getElementById('producttype-dropdown'); // select the dropdown
    
        //Attach the onchange event handler
        select.onchange = function (e) { 
           //iterate through keys in json object
            for (var key in locInfo) {
                if (key == select.options[select.selectedIndex].value) { // check for equality 
                    document.getElementById('iamdiv').innerHTML = locInfo[key]; //Assign result
                }
            }
    
        };
    </script>
    

    You can find the working demo here. Hope this helps you

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题