2010-05-16 117 views
3

首先感謝您檢查我的問題,併爲您提供任何幫助!使用JQuery Ajax調用一個PHP函數

好吧,就像標題所示,我需要從我的索引頁調用php函數,該函數使用JQuery Ajax在我的數據庫中添加了一條新的記錄。此函數將返回一個整數,然後將打印在從中調用它的表單按鈕中。

任何人有一個想法,我會如何做到這一點?任何指導表示讚賞!

Edit: 

So if I'm using a template object I can just call the 
function using ajax and it will return the output? 
What would I use as the URL? index.php? 

Such as... 
function DoVote() { 
    $.ajax({ 
    type:'POST', 
    url: 'index.php', 
    success: function(data) { 
    $('#voteText').html(data); 
} 
}); 

而表單動作屬性張貼我猜?

+0

或者我怎樣才能使用Ajax調用php函數? – NickKampe 2010-05-16 06:29:17

回答

3

是的,創建一個單獨的PHP文件,調用該函數並回顯輸出。然後用AJAX請求加載該php文件。

由於PHP是服務器端語言,jQuery(JavaScript)是客戶端,您不能直接使用使用它調用PHP函數,您可以執行的操作最多的是加載文件。但是,如果該文件有類似<?php echo($object->function()); ?>的文件,則可以加載該文件,實質上調用該函數。

我不確定(您的添加)是否正確。

在任意文件,你有一個PHP函數:

<?php 
    // Called "otherfile.php" 

    // Function you're trying to call 
    function doSomething($obj) 
    { 
     $ret = $obj + 5; 

     return($ret); 
    } 
?> 

而且你有一個文件(稱爲ajaxcall.php),您將與AJAX調用加載。

<?php 
    include("otherfile.php"); // Make the file available, be aware that if that file 
           // outputs anything (i.e. not wrapped in a function) it 
           // may be executed 
    // Grab the POST data from the AJAX request 
    $obj = $_POST['obj']; 

    echo($doSomething()); 
?> 
+0

添加更多問題 – NickKampe 2010-05-16 06:44:41

+0

@Stevie編輯答案 – 2010-05-16 14:21:46

0

ajax請求只是強制一些URL訪問,它運行在那裏的PHP。通過任何附加參數(甚至GET),您可以更改被調用的函數,也可以將它們傳遞給函數本身。