2017-02-10 58 views
0

我怎么能加载文件table.php与我尝试通过的数据,当ajax调用made.I'm与jquery.load方法trysing第二个参数是一个数据数组,但不起作用。传递数据到PHP文件与HTML模板

这是一个基本的例子,我必须让我得到这个错误

Notice: Undefined variable: field in C:\xampp\htdocs\prueba2\table.php on line 2 

的index.php

<?php 
    $datos = array(array('nombre1','apellidos1'),array('nombre2','apellidos2')); 
?> 
<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
</head> 
<body> 
     <h2>Tabla</h2> 
     <div id="tabla"> 
      <table border="1px"> 
      <?php 
       foreach ($datos as $dato) { 
        echo "<tr><td>".$dato[0]."</td><td>".$dato[1]."</td></tr>"; 
       } 
      ?> 
      </table> 
     </div> 

     <form id="search-form" method="POST"> 
      <input type="text" id="search" name='search'> 
      <input type="submit" value="Buscar"> 
     </form> 
     <script 
       src="https://code.jquery.com/jquery-1.12.4.min.js" 
       integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" 
       crossorigin="anonymous"></script> 
     <script type="text/javascript" src="submit.js" ></script> 
</body> 
</html> 

submit.js

$("#search-form").submit(function(event) { 
    event.preventDefault(); 
    $.ajax({ 
     url: "http://localhost/prueba2", 
     data:{ action:"selection" } 

    }) 
    .done(function(data) { 
     $data = { field: $("#search").val()}; 
     $("#tabla").load("table.php", $data); 
    }); 

}); 

table.php

<div id="tabla"> 
    <?=$field?> 
    <table border="1px"> 
     <tr> 
      <td>a</td><td>b</td> 
     </tr> 
</table> 

回答

0

变量$field不存在于table.php。您需要使用$_POST['field']$_GET['field']

+0

工程witn $ _POST ['字段'] ...但我认为,得到是在jQuery上调用的默认方法jQuery – AFS

+0

GET是默认的'load()',除非你调用它与对象 - 对象获取发送作为POST。从[documentation](http://api.jquery.com/load/#request-method):如果数据作为对象提供,则使用POST方法;否则,假定为GET。 –