简体   繁体   English

从JS文件中的数据库中获取数据

[英]Fetch data from database in JS file

I've created a tag input for my user in my site, for that purpose I coded a tag function with dropdown help. 我已经在我的网站上为用户创建了标签输入,为此,我使用下拉帮助对标签功能进行了编码。 So my problem is that, I want to fetch data from data base in JavaScript file. 所以我的问题是,我想从JavaScript文件中的数据库中获取数据。
Js JS

var FormSamples = function () {


    return {
        //main function to initiate the module
        init: function () {

            // use select2 dropdown instead of chosen as select2 works fine with bootstrap on responsive layouts.
            $('.select2_category').select2({
                placeholder: "Select an option",
                allowClear: true
            });

            $('.select2_sample1').select2({
                placeholder: "Select a State",
                allowClear: true
            });

            $(".select2_sample2").select2({
                placeholder: "Type to select an option",
                allowClear: true,
                minimumInputLength: 1,
                query: function (query) {
                    var data = {
                        results: []
                    }, i, j, s;
                    for (i = 1; i < 5; i++) {
                        s = "";
                        for (j = 0; j < i; j++) {
                            s = s + query.term;
                        }
                        data.results.push({
                            id: query.term + i,
                            text: s
                        });
                    }
                    query.callback(data);
                }

            });
            function format(item) {
                opt = $(item.element);
                sel = opt.text();
                og = opt.closest('optgroup').attr('label');
                return og+' | '+item.text;

                }
                $("select").select2({
                formatSelection: format,
                escapeMarkup: function(m) { return m; }
            });


            $(".select2_sample3").select2({
                tags: ['Karachi','Lahore']
            });

        }

    };

}();

In the end of JS file you'll see: JS文件的末尾,您将看到:

$(".select2_sample3").select2({
     tags: ['Karachi','Lahore']
});

Instead of "Karachi","Lahore" I want to fetch tags from data base. 我想从数据库中获取标签而不是“ Karachi”,“ Lahore”。
I am fetching data like this: 我正在像这样获取数据:

    $conn = mysqli_connect($servername, $username, $password, $dbname);
    $sql = "SELECT * FROM tags";
    $result = mysqli_query($conn, $sql);
    mysqli_query ($conn,"set character_set_results='utf8'"); 
    $row = mysqli_fetch_assoc($result);

Any body please help me that how can I fetch data in JS by PHP. 任何人都请帮助我,我如何通过PHP在JS中获取数据。

You can use json_encode in php: 您可以在php中使用json_encode:

$ar = array('Karachi','Lahore');
echo json_encode($ar);

and in javascript: 并在javascript中:

<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var ar = <?php echo json_encode($ar) ?>;
</script>

output: 输出:

['Karachi','Lahore']

You are almost there. 你快到了 Now you can access the relevant data members of $row by selecting based on column name. 现在,您可以通过基于列名称进行选择来访问$row的相关数据成员。 For example you can look at the value of ˚ $row["id"] . 例如,您可以查看˚ $row["id"] Also fetch_assoc type functions work row by row, so you will have to run it for each row , not each column , when you have multiple results. 同样, fetch_assoc类型的函数逐行工作,因此当您有多个结果时,必须针对每一row而不是每一column运行它。 You can store the results in a php array but you will have to output them to the javascript portion of your file, or store them in a file javascript can access, before ending the php portion of your script. 您可以将结果存储在php数组中,但必须将它们输出到文件的javascript部分,或者将它们存储在javascript可以访问的文件中,然后结束脚本的php部分。 Below I write a little about each of your options. 在下面,我将为您介绍每个选项。

  1. Save data obtained form php data query to csv file, from which javascript can read. 将通过php数据查询获得的数据保存到csv文件,可以从中读取javascript。

Take a look at this SO post to learn how you can read data from csv. 看一下这篇SO帖子 ,了解如何从csv读取数据。 So in this example, your php script could read data from a database and then generate, via php, a csv file. 因此,在此示例中,您的php脚本可以从数据库读取数据,然后通过php生成一个csv文件。 Your javascript could then read from the csv file. 然后,您的JavaScript可以从csv文件读取。

  1. Alternately you can write from php directly to the javascript encoded in the same page assuming you can use your script in the same web page and not as a .js include. 或者,假设您可以在同一网页中使用脚本而不是.js包含,则可以直接从php写到同一页面中编码的javascript。 In that case, you can use json_encode to print your php arrays to javascript arrays as described in this SO post . 在这种情况下,您可以使用json_encodephp arrays打印为javascript arrays ,如本SO post中所述

For example, to create two arrays accessible in Javascript of cities and countries I would do this: 例如,要创建两个可以使用Javascript访问城市和国家/地区的数组,我可以这样做:

   <?php
    ...

    $city = array();
    $country = array();
    while($row = mysqli_fetch_assoc($result)){
       array_push($city, $row['city']);
       array_push($country, $row['country']);
    }
    ...?>

    <script>
       var city = <?php echo json_encode($city); ?>;
       var country = <?php echo json_encode($country); ?>;
     ...
    </script>

Here I am assuming you stored the data in a database with column names 'city' and 'country' 在这里,我假设您将数据存储在列名为“ city”和“ country”的数据库中

You should also consider using PDO objects for safer SQL manipulation. 您还应该考虑使用PDO对象进行更安全的SQL操作。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM