用JQuery重定向到不传输表单内容的PHP页面


Redirection with JQuery to PHP page not transmitting form content

我创建了一个网页,它使用JQuery将表单的内容重定向到使用PHP连接到数据库以查找一些内容的另一个网页。不幸的是,表单的内容没有正确传输,因为我得到"通知:未定义的索引:postal_code在C:'wamp'www'mywebsite'target.php在第8行"

my code:

home。

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <form action="/" id="myform">
   <input type="text" name="postal_code" placeholder="Search..." />
   <input type="submit" value="Search" />
  </form>
  <!-- the result of the search will be rendered inside this div -->
  <div id="result"></div>
<script>
$('#myform').submit(function() {
   var url = 'target.php';
   var postal_code = $('#postal_code').val();
   $.post( url, { postal_code: postal_code },
      function( data ) {          
          $( "#result" ).empty().append( data );
      }
    );
   return false;
});

target.php

<?php
try
{
   $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
   $bdd = new PDO('mysql:host=localhost;dbname=mydatabase', 'root', '', $pdo_options);
   $response = $bdd->prepare('SELECT city FROM city_list where postal_code = ?');
   $response->execute(array($_POST['postal_code']));
   echo '<ul>';
       while ($data = $response->fetch())
       {
   ?>
          <br/>The city you entered the postal code is : <?php echo $data['city'];  
       }
       $response->closeCursor();
}
catch (Exception $e)
{
        die('Error : ' . $e->getMessage());
}
?>

您正在搜索$('#postal_code').val();,但是postal_code的输入没有ID。

代替

<input type="text" name="postal_code" placeholder="Search..." />

<input type="text" name="postal_code" id="postal_code" placeholder="Search..." />

它应该可以正常工作