PHP 在同一页面上获取 AJAX 数据
PHP Get AJAX Data on the same page
我需要获取 DOM 元素的宽度,以便稍后使用 PHP 处理数据。 ajax 调用和 PHP 在同一页上。
页面如下所示:
<div id="elem" width="200px"></div>
<script>
let wd = document.getElementById('elem').offsetWidth;
$.ajax({ type: "POST", url: "index.php", data: {"width": wd} });
</script>
<div id="elem2">
<?php
echo $_POST['width'] . 'px';
?>
</div>
所以我有 elem
,它的宽度不固定,我需要获取它,以便稍后在 PHP 中使用它。首先获取宽度很重要,因为 elem
在 elem2
之前呈现,我需要 elem
的宽度才能正确显示 elem2
。
echo $_POST['width']
的当前输出为空。
我看到有人在同一页面上获取 ajax 数据,但他们使用表单输入,但我 POST elem
的宽度。
我不知道这是否对你有帮助,但你可以使用 ajax 的成功来显示 elem2 中 elem1 的宽度:
$.ajax({
type: "post",
url: "index.php", //or somewhere else,
data: { width: wd },
dataType: "json",
success: function( response ) {
document.getElementById("elem2").innerHTML = response.width
}
})
我需要获取 DOM 元素的宽度,以便稍后使用 PHP 处理数据。 ajax 调用和 PHP 在同一页上。
页面如下所示:
<div id="elem" width="200px"></div>
<script>
let wd = document.getElementById('elem').offsetWidth;
$.ajax({ type: "POST", url: "index.php", data: {"width": wd} });
</script>
<div id="elem2">
<?php
echo $_POST['width'] . 'px';
?>
</div>
所以我有 elem
,它的宽度不固定,我需要获取它,以便稍后在 PHP 中使用它。首先获取宽度很重要,因为 elem
在 elem2
之前呈现,我需要 elem
的宽度才能正确显示 elem2
。
echo $_POST['width']
的当前输出为空。
我看到有人在同一页面上获取 ajax 数据,但他们使用表单输入,但我 POST elem
的宽度。
我不知道这是否对你有帮助,但你可以使用 ajax 的成功来显示 elem2 中 elem1 的宽度:
$.ajax({
type: "post",
url: "index.php", //or somewhere else,
data: { width: wd },
dataType: "json",
success: function( response ) {
document.getElementById("elem2").innerHTML = response.width
}
})