简体   繁体   English

调用和编写jquery / javascript函数

[英]Calling and writing jquery/javascript functions

I think I have not got the syntax correct for writing a javascript function and calling it to assign its return value to a variable. 我想我没有正确的语法来编写javascript函数并调用它以将其返回值分配给变量。

My function is: 我的职能是:

getObjName(objId){
  var objName ="";
$.ajax( {
    type : "GET",
    url : "Object",
    dataType: 'json',
    data : "objId="+objId,
    success : function(data) {
    objName = data;
    }
});
  return objName;
}

I am trying to call it and assign it to a variable with: 我试图调用它,并将其分配给一个变量:

var objName = getObjName(objId);

However Eclipse is telling me that "the function getObjName(any) is undefined" 但是,Eclipse告诉我“函数getObjName(any)未定义”

There are two things wrong here. 这里有两个错误。 First, you need to add function before getObjName 首先,您需要在getObjName之前添加function

Secondly, you can't return a variable asynchronously. 其次,您不能异步返回变量。 If you absolutely must do this, you can set the ajax to be synchronous, however this will block the running thread the entire time the ajax call is communicating to the server. 如果绝对必须这样做,则可以将ajax设置为同步,但是这将在ajax调用与服务器进行通信的整个时间段内阻塞正在运行的线程。

function getObjName(objId){
  var objName ="";
    $.ajax( {
        async: false,
        type : "GET",
        url : "Object",
        dataType: 'json',
        data : "objId="+objId,
        success : function(data) {
            objName = data;
        }
    });
  return objName;
}

Have to declare functions with the function keyword: 必须使用function关键字声明函数:

function getObjName(objId){
   //...
}

But anyway, your code would not work. 但是无论如何,您的代码将无法正常工作。 The Ajax call is done asynchronously that means, the function getObjName will return, before the Ajax call is finished and objName will be empty. Ajax调用是异步完成的,这意味着,在Ajax调用完成且objName将为空之前,函数getObjName将返回。

You could define your function to accept a callback, eg : 您可以定义函数以接受回调,例如:

getObjName(objId, cb){
    $.ajax( {
        type : "GET",
        url : "Object",
        dataType: 'json',
        data : "objId="+objId,
        success : cb    // <-- call the callback on success
    });
}

and then later: 然后再:

var objName;
getObjName(objId, function(data) {
    objName = data;    // <-- objName refers to the the variable defined 
                       // outside this function and gets set 
                       // after the Ajax call is finished
});

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

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