将数组从PHP发送到javascript

时间:2017-02-01 08:27:28

标签: php jquery html ajax

在PHP文件中,任何人都可以帮我直接制作一个for循环,我不知道将要选择的行数。

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "mydb";//database details
    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) 
    {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT * FROM mytable";
    $result = $conn->query($sql);
    $myarray = array();
    $index = 0;

    if ($result->num_rows > 0) 
    {
        // output data of each row
        while($row = $result->fetch_assoc()) 
        {
            $myarray[$index] = $row["firstname"];
            $index++;
            $myarray[$index] = $row["lastname"];
            $index++;
            $myarray[$index] = $row["email"];
            $index++;
        }
    } 
    else 
    {
        echo "0 results";
    }
    $conn->close();
?>

Javascript代码包含搜索栏建议代码的javascript,这里我没有提到typeahead javascript文件

var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
        var matches, substringRegex;

        // an array that will be populated with substring matches
        matches = [];

        // regex used to determine if a string contains the substring `q`
        substrRegex = new RegExp(q, 'i');

        // iterate through the pool of strings and for any string that
        // contains the substring `q`, add it to the `matches` array
        $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
            }
        });

        cb(matches);
    };
};

$('#the-basics .typeahead').typeahead({
    hint: true, //here i used typeahead js code though i didnt mentioned here
    highlight: true,
    minLength: 1
}, {
    name: 'states',
    source: substringMatcher(states)
});

2 个答案:

答案 0 :(得分:0)

当您读取值时,可以在这里简化PHP,因为您不需要增加索引:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);//making a connection
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $myarray[] =$row["firstname"];
        $myarray[] =$row["lastname"];//storing in the array
        $myarray[] =$row["email"];
    }
} else {
    echo "0 results";
}
$conn->close();
?>

您可以将结果回显到您需要的Javascript,例如echo($myarray[0])

您的Javascript可能如下所示:

var matches = <?php echo($myarray[0]); ?>

答案 1 :(得分:-1)

您可以通过4种方式将动态内容插入到javascript代码中。

  1. 将javascript内联到您的PHP页面。也就是说,将您的js代码放在<script>标记

  2. 使动态js变量全局化并在php页面中填充它们。您的单独JS文件将能够读取这些全局js变量。

  3. 如果你想为JS创建一个单独的文件,你必须每次都生成它(因为你不能在javascript中使用PHP代码。浏览器无法解释它,服务器无法解释它)
  4. 如果您想强制服务器解释JS文件中的PHP代码,请添加一个处理程序,以便.js由php解释器处理(无论是php模块还是php-cgi),请参阅Clean links to PHP-generated JavaScript and CSS