我正在尝试将视口宽度和高度发送到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>';
?>
答案 0 :(得分:0)
您已向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>';
?>