2009-01-25 146 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