2015-12-02 94 views
-1
function updateChatroom() { 
    $.ajax({ 
     url:'../inc/chatroom_update.php', 
     type:'POST', 
     success:function(response) 
     { 
      $("#chatUpdate").html(response); 
     } 
    }); 
} 

我上面有這個ajax,它放在header.php文件的頭文件中。現在我的header.php包含在我的所有網頁中,這意味着我的ajax中的網址需要更改,因爲我的網頁可以位於不同的文件夾中。我如何使AJAX網址動態?如何動態更改AJAX網址?

在PHP中,如果我想在我的header.php文件鏈接上創建一個動態鏈接。我將設置一個BASE_URL,然後放入文件所在的位置。我如何從PHP到AJAX做到這一點?提前致謝!

+0

從哪裏生成這些動態url? – Dasrath

+0

閱讀此:http://stackoverflow.com/a/24463585/1059101 – Jai

回答

0

爲什麼你不這樣做?

function updateChatroom(url) { 
    $.ajax({ 
     url:url, 
     type:'POST', 
     success:function(response) 
     { 
      $("#chatUpdate").html(response); 
     } 
    }); 
} 

現在你可以用任何url來調用它。

0

爲什麼不只是注入網址&後數據作爲參數。

<script> 
    function updateChatRoom(url, data) { 
     data = data || {}; 

     //I'd suggest validating this against some list. 
     if(!!url) { 
      $.ajax({ 
       url: url, 
       data: data, 
       type:'POST', 
       success:function(response) 
       { 
        $("#chatUpdate").html(response); 
       } 
      }); 
     } else { 
      //Throw 
     } 
    } 
</script> 
0

如果這個功能放在裏面PHP文件,你可以使用類似的代碼到一個波紋管基礎上建立網址,該網頁的要求:

<% 
    $url = $_SERVER['REQUEST_URI']; //returns the current URL 
    $parts = explode('/',$url); 
    $dir = $_SERVER['SERVER_NAME']; 

    for ($i = 0; $i < count($parts) - 1; $i++) { 
    $dir .= $parts[$i] . "/"; 
    } 
%> 
function updateChatroom() { 
    $.ajax({ 
     url: $dir . '../inc/chatroom_update.php', 
     type:'POST', 
     success:function(response) 
     { 
      $("#chatUpdate").html(response); 
     } 
    }); 
} 
1

使用動態頁面名稱:

功能updateChatroom(){

var url="<?php echo basename($_SERVER['PHP_SELF']); ?>"; 
$.ajax({ 
     url:'../inc/'+url, 
     type:'POST', 
     success:function(response) 
     { 
     $("#chatUpdate").html(response); 
     } 
     }); 

}