简体   繁体   English

用JavaScript调用jQuery函数

[英]Calling a jQuery function with JavaScript

I am using jQuery and JavaScript, I need to call the jQuery function inside my JavaScript code. 我正在使用jQuery和JavaScript,我需要在我的JavaScript代码中调用jQuery函数。

My jQuery code: 我的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 ?
}

My ajax.php file has: 我的ajax.php文件具有:

<?php
   session_start();
    ....

   echo "$salary";
?>

My JavaScript function has: 我的JavaScript函数具有:

my.js

function showName(){
    var id = 12;

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

How do I call the jQuery function inside JavaScript code and how do I return the PHP values to jQuery? 如何在JavaScript代码中调用jQuery函数,如何将PHP值返回给jQuery?

I really think you need to separate both things: 我真的认为您需要将这两件事分开:

  1. A function to trigger the Ajax call. 触发Ajax调用的函数。
  2. A function that receive the result from the Ajax call and do whatever you need. 该函数从Ajax调用接收结果并执行所需的任何操作。

Like: 喜欢:

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

Then in your my.js code: 然后在您的my.js代码中:

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

Remember that display() will trigger your Ajax call and the code will continue, then when you get your response (maybe some seconds or ms later) anotherFunction() will be called. 请记住,display()将触发您的Ajax调用,并且代码将继续,然后当您收到响应时(可能在几秒钟或ms之后),将调用anotherFunction()。 That's why Ajax is asynchronous . 这就是为什么Ajax是异步的 If you need synchronous calls, check the documentation about jQuery and Ajax technique. 如果需要同步调用,请查看有关jQuery和Ajax技术的文档。

You call showName from the anonymous function you assigned to the key 'success' in the Ajax request. 您从分配给Ajax请求中键“成功”的匿名函数中调用showName。 The anonymous function you assigned to success is your call back function. 您分配给成功的匿名功能是您的回叫功能。

Review the documentation on the Ajax class . 查看有关Ajax类的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM