【问题标题】:Calling a jQuery function with JavaScript使用 JavaScript 调用 jQuery 函数
【发布时间】:2010-10-03 09:28:02
【问题描述】:

我正在使用 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?

【问题讨论】:

    标签: php javascript jquery ajax


    【解决方案1】:

    我真的认为您需要将两者分开:

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

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

    【讨论】:

    • 在那一行 $("#response").html(data);那不应该是 $("#response").html(response); ???
    【解决方案2】:

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

    评论the documentation on the Ajax class

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多