Return data using ColdFusion and jQuery Ajax

可紊 提交于 2019-12-23 03:54:15

问题


I'm making a request to a cfc file that queries a database. Do I store these results in a struct, array or some other way? And depending on how I store and return the results, how do I handle the pieces from jQuery?
I tried storing the results in an array and only displaying one of the results like so, which did not work:

$.ajax({
    type: "POST",
    url: "/ajax/ajax_test.cfc?method=ajaxTest",
    data:"field1=17",
    success: function(response) {
    var r=response;
    $(".cat_vid_subContainer").empty();
    $(".cat_vid_subContainer").html(r.DATA[2]);
    }
    });

回答1:


Have your CFC return the data as JSON, and modify your ajax request to be expecting JSON.

Assuming CF8+

To have your method return JSON, just append a new querystring name/value pair "returnformat=json".

To have your ajax expect to receive json, just add "dataType: 'json'" to the ajax function.

$.ajax({
  type: "POST",
  dataType: 'json',
  url: "/ajax/ajax_test.cfc?method=ajaxTest&returnformat=json",
  data:"field1=17",
  success: function(response) {
    var r=response;
    $(".cat_vid_subContainer").empty();
    $(".cat_vid_subContainer").html(r.DATA[2]);
   }
});

If your CFC is returning an array, then then jQuery will deserialize the JSON array into a javascript array, and you can access elements of it as you currently do.

Note, its critical that your CFC only return the JSON. If you're returning debugging info, or have a bunch of whitespace before the JSON, jQuery won't be able to deserialize it. Use Firebug or some other similar tool to verify the quality of your returned JSON. Or, just request the url with a browser and view the source.



来源:https://stackoverflow.com/questions/4822649/return-data-using-coldfusion-and-jquery-ajax

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