在页面加载时将变量从PHP传递到jQuery [英] Passing a variable from PHP to jQuery on page load

查看:109
本文介绍了在页面加载时将变量从PHP传递到jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从url中获取引用变量,并在用户首次访问该页面时查询我的数据库. 然后,我需要获取此结果并在Google地图上进行绘制.

I'm trying to take a reference variable from the url, and query my database when the user first visits the page. I then need to take this results and plot on google maps.

<?php 
    include('storelocator/db/config.php');
    include('storelocator/db/db.php');  

    if(isset($_GET['ref'])){

        $ref = stripslashes($_GET['ref']);

        $sql = "SELECT * FROM `markers` WHERE `ref` = \"".$_GET['ref']."\"";

        $result = mysql_query($sql);    
        $row = mysql_fetch_row($result);
        print_r($row);
    }
?>

这是我在索引页顶部的代码,它可以正常工作,print_r给出正确的结果.我只是不确定如何将这些结果传递给jQuery进行绘制. (我知道如何绘图,我基本上需要知道如何将变量$ row ['latlng']传递给jQuery.)

This is my code at the top of my index page, it works fine, the print_r gives the correct results. I'm just not sure how to pass these results to jQuery to be plotted. (I know how to plot, I basically need to know how to pass a variable $row['latlng'] to jQuery.)

谢谢

推荐答案

类似这样的东西

<script type="text/javascript">
var markers = <?php echo json_encode($row) ?>;
</script>

现在markers JavaScript变量将可用于以上所有脚本.

Now the markers JavaScript variable will be available to any scripts following the above.

您可以使用

var latlng = markers.latlng;

虽然我们在这里,但您应该保护查询免受SQL注入.虽然我总是建议使用PDO和参数绑定,但为您提供快速解决方案

While we're here, you should protect your query from SQL injection. Whilst I always recommend using PDO and parameter binding, a quick fix for you would be

$ref = get_magic_quotes_gpc() ? stripslashes($_GET['ref']) : $_GET['ref'];
$sql = sprintf("SELECT * FROM `markers` WHERE `ref` = '%s'",
               mysql_real_escape_string($ref));

这篇关于在页面加载时将变量从PHP传递到jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆