2016-12-16 31 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