2017-08-18 83 views
-1

我在jquery上很新,我想我不完全明白我在做什么。

我想没有这样做重装我的网页检索从我的DB数据:

$('.add-team-member').click(function(e) { 
    e.preventDefault(); 
    $.post('?c=Data&action=getData&class=TeamMember', function(data) { 
     console.log(data); 
    }) 
    .fail(function() { 
     console.log('fail'); 
    }); 
}); 

这里是我的PHP文件:

class DataController extends Controller{ 
    public static function getData() 
    { 
     //retrieve objects from my database and encode them as json string 
     var_dump(json_encode($_GET['class']::findAll())); 
     return json_encode($_GET['class']::findAll()); 
    } 
} 

的执行console.log(数据)给出一个空字符串,并且不调用失败函数。我单独测试了我的php文件,它工作正常。任何建议为谦卑的初学者?谢谢!

编辑:看到你的一些评论让我觉得$ .post可能不是正确的方法来做到这一点。我试图实现的是从我的数据库中检索数据而无需重新加载页面。我的目标是点击我的按钮将插入一个包含团队成员姓名的下拉列表。为此,我需要从我的数据库中获取TeamMembers的所有对象。 $ .post是实现这一目标的好方法吗?

编辑2:好的我知道了!我不知道我实际上需要回显我的数据以将它们传递给我的JS文件。我认为回归声明是在做这项工作。正如我所说,我很新,在这^^谢谢你“不要太多”和“塔拉”你的帮助!你们是真棒:-D

+0

你看过它吗[链接](https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) –

+0

@Taplar没有我的日志是空的 – Cellendhyll

+0

你的代码适用于我。 –

回答

0

做你想要在一个更简单的方法是什么:

首先降低你的代码尽可能。这由下面的逻辑完成。

//This is your HTML 

//This is your form, if any. 
<input id="value_01" type="text"> 
<input id="value_02" type="text"> 

//This is the link to call the JS function. 
<a href="javascript:void(0);" class="add-team-member" id="add-team-member" onclick="addMember();">Add Member</a> 

//This is the div to display the result. You can use your own. 
<div id="fetched_result"> 

</div> 

//This is your JS function to be called on click. 
<script type="text/javascript">  
    function addMember() { 
     //Fetch the values from your form, if any. 
     var value_01 = $('#value_01').val(); 
     var value_02 = $('#value_02').val(); 

     $.ajax({ 
      type: "POST", 
      url: "your-php-script.php", // Name of the php files 
      data: {value_01 : value_01, value_02 : value_02}, 

      success: function(html) 
      { 
       $("#fetched_result").html(html); 
      } 
     }); 
    } 

下面是你的PHP脚本。

<?php 
    if ($_POST) { 
     $value_01 = $_POST['value_01']; 
     $value_02 = $_POST['value_02']; 

     //Process your Posted values with PHP 

     //You need to echo your output. This will be populated in your result div as is. 
     $result = "<strong>" . $fetched_value; 

     echo $result; 
    } 
?> 

希望这项工作。

+0

谢谢,我刚解决了它!我只是不知道我必须回应我的结果xD – Cellendhyll

+0

我发布答案后阅读您的评论:)。快乐编码... –