【问题标题】:How to call a PHP function within a $.getJSON function?如何在 $.getJSON 函数中调用 PHP 函数?
【发布时间】:2017-07-29 03:42:38
【问题描述】:

PHP 函数应该返回一个特定的数字并将其存储到变量 data[i] 中。如何在 $.getJSON 函数中访问 PHP 函数?我使用了一个 PHP CodeIgniter 框架。谢谢!

`$.getJSON("<?php echo site_url('some_contoller/some_funcion');?>", function (data) {
  for (var i = 0; i < data.length; i++) {
            var data[i] = "<?php echo $this->some_PHP_function($with_parameter)?>";
  }

}`

这是我的 PHP 函数:

public function get_report_pictures($report_id) {
  $this->db->select('*');
  $this->db->where('report_id', $report_id);
  $query = $this->db->get('report');
  $data = $query->result();

  return $data;

}

【问题讨论】:

  • 你好。您不能直接访问 PHP Javascript。 PHP 在服务器上运行,Javascript 在浏览器上运行。对于两者之间的交互,请使用 AJAX。
  • 哦,好的,谢谢!那我就用AJAX来调用PHP函数吧?
  • 你能发布你的控制器的功能吗?
  • 我认为这个堆栈答案会得到一些帮助,stackoverflow.com/questions/9904272/…

标签: php json codeigniter getjson


【解决方案1】:

在 javascript 文件 (*.js) 中不能使用 php 代码。

您可以使用 $.ajax() 来调用控制器中的函数。

   $.ajax({
           type: "post",
           url: "some_contoller/some_funcion",         
           dataType :'json',
           success: function(response){
               if(response.status=='success'){
                response.data.forEach( function (item)
                 {
                  var x = item.number;
                   console.log(x);
                 });
                }
           },error:function (jqXHR, textStatus, errorThrown) {
               console.log(textStatus);
              }
         });

在你提到的函数中'some_funcion'

echo  json_encode(array(
                        'status'=>'failed',
                        'data'   => 'number you say ') 
                       );
             exit();

这是我的解决方案。我希望它有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2019-01-20
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多