1

我需要在输入邮政编码时自动填写 CITY: 表单,上面写着“未定义的变量:在线数组..” where value="< ? php $array['navn'] ">

有人可以帮忙吗?

http://i62.tinypic.com/hv5fkl.jpg

<div id="search">
                        <form name="input" action="" method="get">
                            POST:<input type="text" name="postcode"><br><br>
                            City:<input type="text" name="navn" value="<?php $array['navn'] ?>"><br><br>
                            <input type="submit" value="search">
                        </form> 
                    </div>


                    </div>

                   <?php
                        if(isset($_GET['postcode'])){


                        $postcode = $_GET['postcode'];

                        $content = file_get_contents('http://oiorest.dk/danmark/postdistrikter/'. $postcode . '.json');

                        $array = json_decode($content, true);


                            echo $array['navn'];
                            echo "<br>";


                        }
                    ?>
4

1 回答 1

1

You'd want to always initialize variables. What happens is that you're trying to access a variable that hasn't been initialized yet.

<?php

$city = ''; // initialize containers
$postcode = '';

if(isset($_GET['postcode'])){
    $postcode = $_GET['postcode'];
    $content = file_get_contents('http://oiorest.dk/danmark/postdistrikter/'. $postcode . '.json');
    $array = json_decode($content, true);
    // when the request is made, then assign
    $city = $array['navn'];
}

?>

<!-- so that when you echo, you'll never worry about undefined indices -->
<div id="search">
    <form name="input" action="" method="get">
    POST:<input type="text" name="postcode" value="<?php echo $postcode; ?>"><br><br>
    City:<input type="text" name="navn" value="<?php echo $city; ?>"><br><br>
    <input type="submit" value="search">
    </form>
</div>

In this answer, what happens is that, upon first load (no json request yet), the values are empty but they are declared on top.

When you submit the form, then that variable assignment happens and substitutes the values into that container.

Simple Demo

于 2014-11-07T08:22:27.083 回答