I think I have not got the syntax correct for writing a javascript functio开发者_开发技巧n and calling it to assign its return value to a variable.
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"
There are two things wrong here. First, you need to add function
before getObjName
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.
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 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.
You could define your function to accept a callback, e.g. :
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
});
精彩评论