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

标签 php jquery html css viewport

我正在尝试将视口(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/

相关文章:

php - 小部件设计。什么更好 : IFrames or Javascript?

javascript - Magento 时事通讯弹出窗口(模式窗口)在每个页面上弹出。它应该只在主页上弹出

php - UTF-8贯穿始终

jquery data属性获取该元素

javascript - 使用 HTML 和 JS 拖放 2 个以上的图像

javascript - 使用 javascript 或 PHP 根据输入自动减去数字,无需单击按钮

javascript - 在 JQuery 中创建 Bootstrap 警报

javascript - 使用图表js显示的图表不正确

css - Bootstrap "class=text-center"与 CSS "text-align: center"

html - 在 Bootstrap 中用一个按钮填满整个框