问题
I'm trying to call an CFC component with Ajax. But I need to pass the value returned by the CFC to my javascript routine. The done function creates the correct message when I display msg in an alert. But the ret variable is never populated with that value. I need the value returned to alter the javascript data flow.
What am I doing wrong?
var ret = $.ajax({
type: "post",
url: "cfc/CFCSemae.cfc",
data: {
method: "verificaCadastro",
returnformat: "plain",
queryformat: "column",
nro_cadastro: num_cad
},
dataType: "html",
}).done(function(msg){ return msg; });
alert(ret);
回答1:
The following code should do it for you, however understand that when you are doing async requests, you'll only get the result when the callback is executed. Your code will simply call you $.ajax function, but it will not wait for a response (as it if it's in a different thread). When the response is ready, the callback complete is executed. If the response return a success message (HTTP Status 200), the success callback is called, error is called otherwise.
//somewhere in your script
var ret = '';
// then at the ajax request
$.ajax({
type: "post",
url: "cfc/CFCSemae.cfc",
data: { method: "verificaCadastro", returnformat: "plain",
queryformat: "column", nro_cadastro: num_cad },
dataType: "json",
contentType: "application/json; charset=utf-8", // make sure your serverside function can return json
success: function(data) {
//your own validation to check whether 'data' is a valid response
ret = data;
},
error: function(xhr, msg) {
// handle error
}
});
Please read the following article about ajax programming. This will give you a better understanding of what asynchronous programming is: http://en.wikipedia.org/wiki/Ajax_(programming)
Edit: corrected misspelling
回答2:
AJAX is asynchronous, you cannot return a value from the callback with out making a synchronous call. You really don't want to do that.
Provide a callback function for the success: handler. You can add your logic there for placing the returned data into your JavaScript flow.
来源:https://stackoverflow.com/questions/10180544/returning-value-from-coldfusion-cfc-called-with-jquery-ajax