2012-10-10 43 views
-4

可能重複:
Creating jQuery AJAX requests to a PHP function通過AJAX調用PHP函數

我想運行一個非常簡單的公式,

調用Web頁面,並每隔幾秒鐘或者Ajax調用php函數來回顯「Hello World」

<?php 
function test(){ 
    echo "Hello World"; 
} 
?> 
<script type="text/javascript"> 

function testingTimer() 
{ 
    //CALL PHP FUNCTION CALLED TEST 
} 

setInterval('testingTimer()',5000); 
</script> 

我需要的是調用已聲明的php函數的代碼。

+0

閱讀:http://stackoverflow.com/questions/7016701/creating-jquery-ajax-requests-to-a-php-function/7016795#7016795 – NullUserException

回答

0

AJAX無法自行調用任意php函數。 AJAX允許您連接到給定頁面並請求數據。這就是說,你可以使用AJAX來加載給定頁面,並且所有頁面所做的就是調用你的測試函數:

0

谷歌關於如何做ajax調用。這是在許多教程中解釋的基本知識,並且取決於您是否使用框架以及哪些不同。

2

你不能直接調用它。寫AJAX呼叫 URL像myfile.php?action=test和文件myfile.php寫,如果行動GET變量等於測試然後調用這個函數,不要忘記退出代碼,以防止任何其他輸出的代碼。

0

您可以張貼例如東西:

function testingTimer() 
{ 
    $.post(URL, 
      { 
      foo : 'foo' 
      } 
    ); 
} 

,並在PHP檢查崗:

if (isset($_POST['foo'])) 
    test(); 
0

您應該使用jQuery使用ajax function

您不應該使用setInterval,而是在服務器響應之後使用setTimeout,因爲如果服務器的響應時間超過5000秒,那麼您將同時有兩個請求。 如果您想要超時,可以在jqXHR對象上始終看到中止函數。

例如,你可以這樣做:根據您的示例代碼

function refresh() { 
    $.ajax({ 
     type: 'GET', // can be POST or GET 
     url: 'page.php' // php script to call 
    // when the server responds 
    }).done(function(response) { 
     console.log(response); 
     // call your function automatically 
     setTimeout(refresh, 5000); 
    }); 
} 
0

我假設你正在試圖做的這一切都在一個單一的文件。您遇到的問題是PHP在頁面加載之前/在服務器端運行。一旦加載,不能在沒有刷新的情況下重新執行。

您需要將PHP放在單獨的文件中,以便可以通過AJAX通過HTTP調用它並返回響應。

因此,像這樣(如果使用jQuery):

$.ajax('helloworld.php', function(data){ 
    alert(data); 
}, 'html'); 

應與世界你好,如果正確實施彈出。