如何在模式窗口中将 JQuery 变量转换为 PHP 变量而不刷新页面


How to transfer JQuery variable into PHP variable in a modal window without page refresh

我是这个客户端变量到服务器变量传输过程的新手。

本质上,我有一个谷歌地图 api 函数,并在地图上有一个标记来表示我的 PHP Web 应用程序的用户表 (MySQL) 中的用户名。当我双击该地图标记时,我的 Jquery 函数会弹出一个模态,我能够在 .但是,我现在需要能够在PHP变量($chosenUser)中访问此值,而无需任何"提交"或页面刷新,以便我可以调用我的PHP函数 - getUserChannelID($chosenUser),并继续其余的逻辑。

我的断开连接是能够访问 id/name 上的值作为 #chosenUser 并将其传输到 PHP 变量$chosenUser而无需"提交"或页面刷新。下面的所有代码都在同一页面上。

我正在 SF 帖子中阅读有关使用 AJAX 来执行此操作的信息,但由于我对 AJAX 相当幼稚,我对如何在没有表单"提交"或页面刷新的情况下在同一页面上完成此操作感到困惑。

您能否帮助更正下面的代码,以便我可以 #chosenUser PHP 变量$chosenUser获取该值?

这是我的代码都在同一个PHP文件中。

<?php
require_once("classes/autoload.php");
$db = new Database();
....
?>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" ></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid" style="margin: 0 auto;">            
    <div style="height: 100%; position: relative; top:30px;">
            <div id="map" style="height: 100%;"></div>
    </div>
    <div class="modal fade" id="showChannel" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Channel Preview</h4>
                </div>
                <div class="modal-body">
                    <div>
                       <input type="hidden"  id="chosenUser" name="chosenUser" value="">        
<!-- This is where I need help. How do I transfer that value I am getting for "chosenUser" above into the PHP variable $chosenUser - ideally the code in the next line would need to be executed -->
                       <?php $channelId = $db->getUserChannelID($chosenUser); ?>
                       .....
                   </div>
                </div>
             </div>
        </div>
     </div>
</div>
</body>
</html>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.20&sensor=false"></script>
<script src="multiple_marker/oms.js"></script>
<script type="text/javascript">
var mapMarkers = [];
var infowindow = null;
var infowindowOpen;
var map, oms;
var gm = google.maps;
var markerIcons = new Array();
var gmarkers = [];
function getCoords() {
    $.ajax({
        url: "markers.php",  // this markers.php provides the value of "Locations" array used below
        type: "POST",
        data: {
            foo: "bar"
        },
        dataType: "json",
        success: function (returnedData) {
            console.log(returnedData);
            if(!spiderify)
                moveMarkerMap(returnedData);
            //window.setInterval(getCoords, 10000);
            window.setTimeout(getCoords, 2000);
        }
    });
}
function MarkerMap(json) {
    var iconBase;
    oms.addListener('click', function (marker) {
        console.log('clicked');
    });
    if ((json.Locations.length > 0)) {
        for (i = 0; i < json.Locations.length; i++) {
            var location = json.Locations[i];
            var username = location.username; // I am getting the value of username here
            var myLatlng = new gm.LatLng(location.Lat, location.Long);
            var marker = new gm.Marker({
                    position: myLatlng,
                    map: map,
                    username: username,
                });
            var infowindow = new gm.InfoWindow();
            var div = document.createElement('DIV');
            gm.event.addListener(marker, 'dblclick', (function (marker, div, infowindow) {
                    return function () {
                        $('#showChannel').modal('show');
                        $('#chosenUser').val(marker.username); //passing the value of marker.username to the modal input id/name="chosenUser"
                    };
                })(marker, div, infowindow));
                gmarkers[id] = marker;
            }
        }
        window.map = map;
        window.oms = omg;
    }
    gm.event.addDomListener(window, 'load', initialize);
</script>

好吧,你不能以你想象的方式在PHP和JS之间进行完全的通信。PHP 是在页面加载时执行的,在显示任何内容之前,在任何 javascript 发送到客户端之前,因此不可能按照您希望的方式执行。

你可以做的是在页面加载完成后,使用 javascript 调用 PHP 脚本。你可以随时这样做,使用延迟循环,在单击按钮时,你可以以任何方式调用你的javascript函数。这样,您可以将信息从javascript发送到PHP,当PHP脚本完成运行时,它可以将信息报告给javascript。

你想要一个来自 PHP 的 js 变量,有多种方法可以做到这一点,例如 POST 或 GET 请求。我将使用 POST 发布一个示例,这与你用来发送表单的东西相同。你需要包含jQuery才能正常工作。

.JS

var myVar = "my info";
var myVar2 = "my other info";
$.post("myscript.php", {
info1: myVar,
info2: myVar2
}, function(answer) {
// answer will contain whatever the PHP script printed
// in this example answer will be "success"
alert(answer);
} );

.PHP

$var1 = $_POST['info1'];
$var2 = $_POST['info2'];
if(!empty($var1) && !empty($var2))
{
    echo "success";
}

现在由您来实施它。