Returning value from Coldfusion CFC called with JQuery Ajax

安稳与你 提交于 2019-12-12 17:34:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!