使用JavaScript调用jQuery函数

时间:2009-01-25 05:12:24

标签: php javascript jquery ajax

我正在使用jQuery和JavaScript,我需要在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?

2 个答案:

答案 0 :(得分:5)

我真的认为你需要把两件事分开:

  1. 触发Ajax来电的功能。
  2. 从Ajax调用接收结果并执行所需操作的函数。
  3. 像:

    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);
    }
    

    请记住,display()将触发您的Ajax调用,代码将继续,然后当您收到响应时(可能会在几秒或几秒后),将调用anotherFunction()。这就是Ajax 异步 的原因。如果您需要 同步 调用,请查看有关jQuery和Ajax技术的文档。

答案 1 :(得分:0)

您从分配给Ajax请求中的密钥“success”的匿名函数中调用showName。您分配给成功的匿名功能是您的回叫功能。

审核the documentation on the Ajax class