2016-12-16 77 views
1

我想在我加载网页的时候,在GET中添加屏幕的宽度和高度,以便我的页面可以使用这些var重定向到特定页面。Ajax,add GET var onload

我看过的功能,似乎我应该使用window.screen.widthwindow.screen.height

而且,我想通了,我应该使用$.get()发送变量。

所以我出来这个脚本,但我假设我混合JS和AJAX,如果没关系,我不会。最重要的是,当我的页面加载时,我不知道如何运行这个函数。

$(document).ready(function() { 
    ratio(); 
function ratio() { 
    var Vorientation; 
    if(window.screen.width>window.screen.height) 
    { 
     Vorientation = 1; 
    } 
    else 
    { 
     Vorientation = 2; 
    } 
    $.get("index.php?orientation="+Vorientation); 
    alert("ok"); 
} 
    }); 

下面是HTML:

<body> 

<?php 
if(isset($_GET['orientation'])) 
{ 
echo"ok"; 
} 
?> 

</body> 
+2

'混合js和ajax' :AJAX不是一种语言,它是一种使用JavaScript从服务器(例如PHP代码)中检索响应的方式,通常用于基于用户i在页面上生成内容NPUT。 '.get'是jQuery(这是一个js库)执行ajax GET请求 –

+1

@asdf_enel_hak实际上,OP使用它的方式,它是一个全局变量。你说得对;它应该在if之前声明,如'var Vorientation;' – qxz

回答

2

运行时,您的网页加载功能,你必须wrap代码$(document).ready(function(){ });功能。

使用此:

$(document).ready(function(){ 
    window.Vorientation=0; 
    ratio(); 
    function ratio() { 
     if(window.screen.width>window.screen.height) 
     { 
      Vorientation = 1; 
     } 
     else 
     { 
      Vorientation = 2; 
     } 
     $.get("index.php", { orientation: Vorientation}) 
      .done(function(data) { 
       alert("Data Loaded: " + data); 
      }); 
    } 
}); 
+0

我认为Vorientation需要在if/else之外声明吗? – EQuimper

+1

它需要首先声明。使用全球不在这里 – qxz

2

你只需要jQuery的添加到您的脚本,并在文档中添加代码准备功能https://learn.jquery.com/using-jquery-core/document-ready/

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
$(function() { 
    ratio(); 
    function ratio() { 
     var Vorientation; 
     if(window.screen.width>window.screen.height) { 
      Vorientation = 1; 
     } else { 
      Vorientation = 2; 
     } 
     $.get("index.php", { orientation: Vorientation}) 
      .done(function(data) { 
       alert("Data Loaded: " + data); 
      }); 
    } 
}); 
+0

现在我已经有一个数据加载警报..我的链接仍然是相同的,我不能看到'?orientation = Vorientation' – Ezhno

+0

@Ezhno,你有错误在控制台? –

+1

AJAX请求发生在后台。他们不会更改浏览器地址栏中的网址;他们只是将响应数据返回给您的回调函数(这里是'data')。 – qxz