2012-12-01 22 views
0

我想通過jQuery將ID傳遞給urlstring而無需刷新jQuery和#標籤,以便我可以通過php $_get['ID']函數獲取ID。通過jquery傳遞ID到url字符串,然後通過PHP選擇它沒有頁面刷新?

但問題是,

  1. 如果我使用#,頁面沒有得到刷新,但是PHP也從URL挑ID。
  2. 如果我不使用#,那麼php會選擇該ID,但Page會刷新。

我想傳遞一個id到php而不刷新頁面。

//javascript 
function com(id) { 
    location.href = '#?ID=id'; //by this way way,page doesn't refresh, ID appears in the url string but ID is not picked by PHP as # is there 
    // location.href = '?ID=id'; this way way, ID appears in the url string , ID is also picked by PHP as # is there.But page get refreshed. 
    $.ajax({ 
     type: "Post", 
     url: "getdata.php", 
     async: true, 
     cache: false, 
     success: function(data) {}, 
    }); 
}​ 

 

//php for getdata.php 
<?php echo $_GET['ID']; ?> 
+3

你必須有一個頁面刷新因爲PHP是服務器端。它在重新加載之前無法獲取url中的更改。但阿賈克斯可能是一個更好的辦法 – 2012-12-01 06:43:20

回答

2

你需要教育自己的服務器端與客戶端操作。 Javascript是客戶端。服務器(在你的情況下運行PHP)不知道什麼是JavaScript在做什麼,除非你發回一些信息。這可以通過頁面刷新或通過ajax(簡單地放置)來完成。

你想要的是ajax,它是一個返回服務器的異步請求。然後,服務器可以處理它並選擇將信息傳遞迴頁面。看看jQuery的ajax

更新基於更新後的評論:

function com(id) { 
    //forget about appending the id. This isn't doing anything. 
    //You can use it for informational purposes or so that if someone cuts and pastes 
    //the link you can handle it server side appropriately. 
    location.href = '#?ID=id'; 

    //instead focus on this call. append your query string to the url  
    $.ajax({ 
     type: "POST", 
     url: "getdata.php?ID=12345", 
     async: true, 
     cache: false, 
     success: function(data) { 
      alert(data); //should alert the id processed by php 
     }, 
    }); 
}​ 
+0

我已編輯我的問題.Plz審查現在 –

+0

@AanaSaeed - 更改網址,而不刷新頁面不通知服務器的任何東西。所以你需要放棄這一思路。而是專注於你的ajax調用。通過調用'url:「getdata.php?ID = 12345」'接收頁面,getdata.php可以使用'$ _GET ['id']'解析出id。 – mrtsherman

相關問題