2014-03-27 32 views
0

我在我的頁面上的.html文件中有這個腳本,我試圖從這裏運行getip.php文件,而不是將文件重命名爲.php。我試過這個Ajax調用,但它不工作,並沒有在logfile.txt中記錄ip。請讓我知道我做錯了什麼。ajax運行php文件

阿賈克斯.html文件的頭部:從getip.php

<script> 
    $(document).ready(function() { 
     $.ajax({ 

       type: "GET", 
       url: "getip.php", 

      }); // Ajax Call 
     }); //event handler 
    </script> 

代碼:

<?php 
// location of the text file that will log all the ip adresses 
$file = 'logfile.txt'; 

// ip address of the visitor 
$ipadress = $_SERVER['REMOTE_ADDR']; 

// date of the visit that will be formated this way: 29/May/2011 12:20:03 
$date = date('d/F/Y h:i:s'); 

// name of the page that was visited 
$webpage = $_SERVER['SCRIPT_NAME']; 

// visitor's browser information 
$browser = $_SERVER['HTTP_USER_AGENT']; 

// Opening the text file and writing the visitor's data 
$fp = fopen($file, 'a'); 

fwrite($fp, $ipadress.' - ['.$date.'] '.$webpage.' '.$browser."\r\n"); 

fclose($fp); 
?> 
+1

響應處理..'.done(功能(數據))''https://api.jquery.com/jQuery.ajax/另外,你不需要一個類型,你也可以這樣做:'$ .ajax(「getip.php」)。done(function( ){alert(「done」);})。fail(function(){alert(「failed」);});' – briosheje

+1

當您直接訪問它時,php文件是否工作?我會先測試一下,然後一旦確定工作正常,就使用Firebug(firefox extention)來查看ajax正在做什麼。你應該在你的ajax調用上有一個.done和.fail函數,這樣你就可以知道發生了什麼 – jdcookie

+0

@ Cookie_J5 PHP文件確實有效。 – Steven

回答

1

你試過$.post()功能呢?例如:

<script> 
    $(document).ready(function() { 
     $.post('getip.php'); // Ajax Call 
     }); //event handler 
</script> 

您也可以添加一個回調作爲第二個參數。

+0

Post功能也不起作用。 – Steven

+0

再次嘗試了您的代碼,事實上這確實起作用。我在ajax調用中留下了一些我寫的不起作用的東西。謝謝您的幫助 – Steven

0

我會使用完整的URL進行ajax調用。根據您的框架,您可能不會達到預期的終點。你可以嘗試echo 'test';在你的PHP文件並添加一個做處理您的Ajax調用,以確保你打擺在首位的PHP文件:

.done(function(data) { 
    alert(data); 
});