php echo mysql数组导致ajax

时间:2014-03-20 22:09:40

标签: php jquery mysql ajax arrays

以下function是我的controller代码,由ajax请求调用:

function search_featured_candidates() {       
   $skills = $this->input->post('skills');
   $this->load->model('Featured_candidate', 'featured', TRUE);
   $result = $this->featured->get_featured_candidates_by_skills($skills);
   if ($result) {
      $str = "";
      foreach ($result as $row) {
          $str .= "Name: " . $row->candidate_name . "<br/>";
          $str .= "Exp: " . $row->experience . "<br/>";
          $str .= "Skills: " . $row->skills . "<hr/>";
      }
      $html = $str;
      echo json_encode(array('html' => $html, 'success' => TRUE));
      } else {
          $html = 'No Candidates Found!';
          echo json_encode(array('html' => $html, 'success' => FALSE));
      }
 }

我的view代码:

<script>
$(function() {
    $("#featured_candidates").on("change paste keyup", function() {
        $.ajax({
            type: "POST",
            url: "<?php echo base_url(); ?>mypage/search_featured_candidates/",
            data: {skills: $(this).val()},
            dataType: "json",
            success: function(data) {
                if (data.success === true) {
                    $("#featured").html(data.html);
                } else {
                    $("#featured").html(data.html);
                }
            }
        });
    });
});
</script>

 <div class="panel-body">
        <div>
            <input type="text" style="width: 100%" 
             name="featured_candidates" id="featured_candidates" 
             placeholder="keyword / skills" title="Featured Candidates" 
             />
            <br/><hr/>
        </div>
        <div id="featured">
            <?php
            foreach ($result as $row) {
                echo "Name: " . $row->candidate_name . "<br/>";
                echo "Exp: " . $row->experience . "<br/>";
                echo "Skills: " . $row->skills . "<hr/>";
            }
            ?>
        </div>
    </div>

现在我正在尝试使用result array显示ajax,就像我使用view在我的foreach代码中显示的一样。所以要使用ajax显示它我已经在$str中的控制器方法中连接了数组但是当我将控制器方法更新为此时它不起作用:

 function search_featured_candidates() {       
   $skills = $this->input->post('skills');
   $html = $skills ;
   echo json_encode(array('html' => $html, 'success' => TRUE));
 }

它工作正常..任何帮助或建议将是一个很大的帮助...提前感谢..

2 个答案:

答案 0 :(得分:0)

你这里有个错误

foreach ($result as $row) {
    echo "Name: " . $row->candidate_name . <br/>";
    echo "Exp: " . $row->experience . "<br/>";
    echo "Skills: " . $row->skills . "<hr/>";
}

你忘记了&#34;

. $row->candidate_name . "<br/>";
                    //   ^ You forgot the "

答案 1 :(得分:0)

您的问题的表述使您很难知道问题的确切位置。但是从快速查看,您通常必须设置正确的标头,以便使用PHP输出json格式的数据。

尝试在执行echo之前添加此内容,这可能会解决您的问题:

header('Content-Type: application/json');