简体   繁体   中英

AJAX request in ColdFusion

How can I do a AJAX request in ColdFusion?

I have my javascript:

function getdata(){
    var formElements=document.getElementById("CFForm_1").elements;    
    var data=[];
    for (var i=0; i<formElements.length; i++){
        if(formElements[i].name == 'customersid')
            data.push({'customersid':document.getElementById("customersid").value});
        if(formElements[i].name == 'customerstoid')
            data.push({'customerstoid':document.getElementById("customerstoid").value});
    }

    $.ajax(
    {
        type: "get",
        url: "components/BillingCalc.cfc",
        data: {
                method:"ajaxGetTotalCost",
                data: data.join()
            },
        dataType: "json",
        success: function( objResponse ){

        }
    });
  }

My component:

component displayName="Calc" {

remote function ajaxGetTotalCost(data){
    data = deserializeJSON(arguments.data);
    WriteDump(data); abort;
}

I am getting the error: JSON parsing failure at character 2:'o' in [object Object],[object Object] Does anyone knows how to do AJAX request in CF?

This function:

remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
WriteDump(data); abort;
}

is not complete. It's at the stage where you have to call it from a ColdFusion page, not with javascript. That will enable you to see the results of the writedump(data) command to ensure it's what you expect. You have to add more code to the function to get it to produce a variable javascript can receive, and then return that variable to whatever is calling the function.

The issue is related to dataType attribute you are passing with $.ajax() method. dataType: "json" indicates your AJAX request is expecting JSON data as a response. But in your case you are simply returning DUMP of the deserialized JSON, which is HTML not JSON . So if you want it to work properly, then you need to return JSON data from your ColdFusion function. You can try this and see if it works.

remote function ajaxGetTotalCost(data){
   data = deserializeJSON(arguments.data);
   return serializeJSON(data));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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