如何将PHP变量与Typeahead变量

时间:2018-04-07 22:00:59

标签: javascript php html ajax

我已经把它减少到尽可能简单。我创建了一个完美运行的typeahead变量。 但我需要传递两个与typeahead无关的其他变量$ php_var1和$ php_var2。 PHP变量在中定义 start.php。 typeahead脚本调用search_script.php然后调用cart.php。 cart.php是我需要的两个PHP变量 被传递给。在此先感谢您的任何帮助

start.php

<?php
  $php_var1 = "my php variable 1";
  $php_var2 = "my php variable 2";
?>


<script>

$(document).ready(function() {

    var php_var1 = <?php echo $php_var1; ?>;
    var php_var2 = <?php echo $php_var2; ?>;


    $('#my_input').typeahead({
        source: function(query, result) {
            $.ajax({
                url: "search_script.php",
                method: "POST",
                data: {
                    query: query
                },
                dataType: "json",
                success: function(data) {
                    result($.map(data, function(item) {
                        return item;

                    }));
                }

            })
        },
        updater: function(item) {
            location.href = 'cart.php?shop_name=' + item
            return item
        }
    });

    });

</script>

<form action="cart.php" action="post">

<input type="text"  id="my_input" placeholder="Typeahead Search" />

</form>

search_script.php

<?php

$php_var1  = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2  = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";

$connect = mysqli_connect($servername, $username, $password, $dbname);
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = " SELECT * FROM all_shops WHERE p_shop_name LIKE '%".$request."%'";

$result = mysqli_query($connect, $query);

$data = array();

if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["p_shop_name"];
}
echo json_encode($data);

}
?>

cart.php     

$php_var1  = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2  = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";

echo $php_var1;
echo $php_var2;

?>

2 个答案:

答案 0 :(得分:0)

你需要在php输出周围引用以生成javascript字符串

var php_var1 = "<?php echo $php_var1; ?>";
var php_var2 = "<?php echo $php_var2; ?>";

答案 1 :(得分:0)

Stackoverflow是一个很好的资源,但有时候你没有得到答案,所以你需要坚持不懈并继续努力。我昨天整天都在做这件事而且无法弄明白。醒来这个AM,它来找我。答案如下。在预先输入的脚本中,更改以下行

location.href = 'cart.php?shop_name=' + item      

location.href = 'cart.php?shop_name=' + item + '&php_var1=<?php echo $php_var1 ?>' + '&php_var2=<?php echo $php_var2 ?>'