gpt4 book ai didi

php - jquery 视口(viewport)信息未传递给 php

转载 作者:行者123 更新时间:2023-11-28 07:20:58 25 4
gpt4 key购买 nike

我正在尝试将视口(viewport)宽度和高度发送到 PHP 文件,但失败了!

我知道这个或更多关于传递给 PHP 的类似问题已经被问过,我也一直在研究这些问题。但是,我还没有弄清楚为什么它对我不起作用...

我得到以下输出,如果数据已传递,第二行将与第一行匹配:

Your viewport width is 1519x766
Width is: 880 and Height is 495

我只是无法获得传递给 PHP 部分的信息 - 在一个文件和两个文件中都这样尝试过,然后我在其中调用 php 文件使用:

<?php include 'panzoom.php';?>

我在头部使用这段代码:

<script>
var viewportwidth;
var viewportheight;

viewportwidth = window.innerWidth,
viewportheight = window.innerHeight

document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');

$(document).ready(function() {
$.ajax({
url: 'http://localhost/index.php',
type: 'POST',
dataType: 'json',
data: {
width : viewportwidth,
height : viewportheight
}
});
});
</script>

<?php
$GLOBALS['directory'] = "photos/frontpage/";

if(isset($_POST['width']) && isset($_POST['height'])) {
$GLOBALS['width'] = $_POST['width'];
$GLOBALS['height'] = $_POST['height'];
}else{
$GLOBALS['width'] = 880;
$GLOBALS['height'] = 495;
}

$width = $GLOBALS['width'];
$height = $GLOBALS['height'];

echo '<p>Width is: ' . $width . ' and Height is ' . $height . '</p>';
?>

最佳答案

您已经向 PHP 脚本发送了一个 JSON 字符串,它被称为 data 因此您应该寻找 $_POST['data']

此外,由于它是作为 json 字符串发布的,为了在 PHP 中理解它,您通常使用 json_decode()

将它解码为数组或字符串

您也不需要在 javascript 中创建所有变量来弄乱全局命名空间。

那么试试这个

<script type="text/javascript">
document.write('<p>Your viewport width is '+
window.innerWidth+'x'+window.innerHeight+'</p>');

$(document).ready(function() {
$.ajax({
url: 'index.php',
type: 'POST',
dataType: 'json',
data: {
width : window.innerWidth,
height : window.innerHeight
}
});
});
</script>

<?php
$GLOBALS['directory'] = "photos/frontpage/";

if( isset($_POST['data']) ) {
$obj = json_decode($_POST['data']);

$GLOBALS['width'] = $obj->width;
$GLOBALS['height'] = $obj->height;
}else{
$GLOBALS['width'] = 880;
$GLOBALS['height'] = 495;
}

$width = $GLOBALS['width'];
$height = $GLOBALS['height'];

echo '<p>Width is: ' . $width . ' and Height is ' . $height . '</p>';
?>

关于php - jquery 视口(viewport)信息未传递给 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32091223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com