简体   繁体   English

来自codeigniter控制器的值,以查看和显示内部javascript变量作为数组

[英]value from codeigniter controller to view and display inside javascript variable as array

I have a textbox with autocomplete functionality. 我有一个具有自动完成功能的文本框。 My Code is, 我的代码是

<script>
  $(function() {
    var items = [ 'France', 'Italy', 'Malta', 'England', 
        'Australia', 'Spain', 'Scotland' ];

    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }

    $( "#skills" )
      .autocomplete({
        minLength: 0,
        source: function( request, response ) {
          response( $.ui.autocomplete.filter(
            items, extractLast( request.term ) ) );
        },
        focus: function() {
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( ", " );
          return false;
        }
      });
  });
</script>

The above code is working fine. 上面的代码工作正常。 Now the problem is, I want to display values from database instead of var items = [ 'France', 'Italy', 'Malta', 'England', 'Australia', 'Spain', 'Scotland' ]; 现在的问题是,我想显示数据库中的值而不是var items = [ 'France', 'Italy', 'Malta', 'England', 'Australia', 'Spain', 'Scotland' ]; . I want to change values inside variable item . 我想更改变量item内的值。

My codeigniter controller code is, 我的codeigniter控制器代码是

$data['skills'] = $this->workdone->getAllSkills();
$this->load->view($page, $data);

My HTML code is, 我的HTML代码是

<input type="text" name="skills" id="skills">

I have tried a lot. 我已经尝试了很多。 Is there any solution. 有什么解决办法。

The best way to do it is passing the value over from Codeigniter to frontend it via AJAX. 最好的方法是通过AJAX将值从Codeigniter传递到前端。

The easy way to do it is to print it out like: 最简单的方法是像这样打印出来:

var items = ["<?=implode('","',$skills)?>"];

AJAX Example (Better way) AJAX示例(更好的方式)

Your jQuery will use $.get(): 您的jQuery将使用$ .get():

var items = [];
$.get(YOUR_CONTROLLER_URL, function(data){
    items = data.skills;
});

Your controller code would print JSON: 您的控制器代码将输出JSON:

$this->output
        ->set_status_header(200)
        ->set_content_type('application/json', 'utf-8')
        ->set_output(json_encode($data))

STEP 1: CREATE ARRAY ON BASIS OF QUERY WHICH STORES ARRAY HAVING ALL ITEMS FROM DATABASE...FOR EX: $all_items 第1步:根据存储数据库中所有项的查询来创建数组...例如EX:$ all_items

STEP 2:Now you just have to use foreach loop to store php array value in javascript array.. 步骤2:现在,您只需要使用foreach循环将php数组值存储在javascript数组中即可。

<script type="text/javascript" language="javascript">
var all_state = new Array();
<?php foreach($all_items as $k => $v){ ?>
    all_state.push('<?php echo $v; ?>');
<?php } ?>
</script>

STEP 3: Now item array in java script will contain all states!!Thats All 步骤3:现在Java脚本中的项目数组将包含所有状态!

I do not endorse any hacky techniques that use array/string functions to mock up a javascript array/object. 我不认可任何使用数组/字符串函数模拟JavaScript数组/对象的黑客技术。

It doesn't get simpler or more stable than using json_encode() . 没有比使用json_encode()更简单或更稳定的了。

If your controller looks like: 如果您的控制器看起来像:

$data['countries'] = ['France', 'Italy', 'Malta', 'England', 'Australia', 'Spain', 'Scotland'];
                     // these are countries, not skills
$this->load->view($page, $data);

Then your view merely needs to declare the client-side variable inside a script tag prior to executing the custom function. 然后,您的视图只需要在执行自定义函数之前在script标记内声明客户端变量。

echo '<script>let countries = ' , json_encode($countries) , ';</script>';

This will make the one-dimensional array available to your client-side script and print the following into the document: 这将使一维数组可用于您的客户端脚本,并将以下内容打印到文档中:

<script>let countries = ['France', 'Italy', 'Malta', 'England', 'Australia', 'Spain', 'Scotland'];</script>

Why is json_encode() so perfect? 为什么json_encode()如此完美? Because it will only use quoting when the datatype requires it AND it will automatically escape quotes within values. 因为它仅在数据类型需要时才使用引号,并且它将自动转义值中的引号。 This means no matter what values you pass, your script won't break (at that point anyhow). 这意味着无论您传递什么值,脚本都不会中断(无论如何在那时)。

If you are passing several pieces of data to the client-side, you can send them all as a single object declaration (containing many key-value pairs), or you can pass each value separately . 如果要将多个数据传递给客户端,则可以将它们全部作为一个对象声明(包含许多键值对)发送, 也可以分别传递每个值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 CodeIgniter:将Javascript数组从View传递到Controller,然后存储到数据库 - CodeIgniter: Pass Javascript Array from View to Controller then store to Database 从控制器获取数组的值以在Codeigniter中使用Ajax查看 - getting the value of a array from controller to view with ajax in codeigniter 无法将数组值从Javascript传递到Codeigniter控制器 - Could not pass array value from Javascript to Codeigniter controller 将视图中的JavaScript变量值分配给控制器变量 - Assign JavaScript variable value from view to controller variable 如何将变量从控制器传递到不在视图内的javascript? - How to pass variable from controller to javascript that is not inside a view? 通过POST方法在Codeigniter中将javascript变量从视图发送到控制器,但是在控制器中aaray显示为空 - Sending javascript variable from view to controller in Codeigniter by POST method but in controller post aaray showing empty 使用codeigniter在视图上从javascript调用控制器 - call controller from javascript on view using codeigniter 将数据数组从视图传递到Controller Codeigniter - Pass data array from view to Controller codeigniter 从视图,代码初始化器中获取控制器中的传递值 - Getting passed value in controller from view, codeigniter CodeIgniter - 如何将值从视图传递到控制器? - CodeIgniter - How to pass a value from a view to a controller?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM