2009-01-25 112 views
0

我正在使用jQuery和JavaScript,我需要在JavaScript代碼中調用jQuery函數。用JavaScript調用jQuery函數

我的jQuery代碼:

function display(id){ 
    $.ajax({ 
     type:'POST', 
     url: 'ajax.php', 
     data:'id='+id , 
     success: function(data){ 
      $("#response").html(data); 
     }//success 
    }); //Ajax 

    //Here I need to return the ajax.php salary 
    //return ? 
} 

我的ajax.php文件有:

<?php 
    session_start(); 
    .... 

    echo "$salary"; 
?> 

我的JavaScript函數有:

my.js 

function showName(){ 
    var id = 12; 

    var a = display(id); //Here I need to call the jQuery function display(). 
} 

下如何調用內部的JavaScript jQuery函數代碼以及如何將PHP值返回給jQuery?

回答

5

我真的覺得你需要兩件事分開:

  1. 該功能可以觸發Ajax電話。
  2. 從Ajax調用接收結果並執行所需操作的函數。

像:

function display(id){ 
    $.ajax({ 
    type:'POST', 
    url: 'ajax.php', 
    data:'id='+id , 
    success: anotherFunction; //Ajax response 
    }); 
} 
在my.js代碼

然後:

display(2); 
function anotherFunction(response){ 
    // Here you do whatever you need to do with the response 
    $("#response").html(data); 
} 

記住顯示器()將觸發Ajax調用和代碼將繼續,然後當你你的迴應(也許幾秒或者幾秒後)anotherFunction()將被調用。這就是爲什麼阿賈克斯是異步。如果您需要同步調用,請查看關於jQuery和Ajax技術的文檔。

+1

該行 $(「#response」)。html(data); 是不是應該是 $(「#response」)。html(response); ??? – AceMark 2010-03-29 14:52:31