简体   繁体   中英

retrieve data with json using CoffeScript in rails

I'm a newlye developer rails application and Coffescript

I have this CoffeScript code to get some data using ajax with the get method and json:

jQuery ->
  $("#detalleliquidacion_nit").change ->
    campo1 = document.getElementById("detalleliquidacion_nit")
    document.getElementById("detalleliquidacion_proveedor_id").value = ""
    document.getElementById("detalleliquidacion_nombreproveedor").value = ""
    jQuery.getJSON "/proveedores/obtenerdatos/" + campo1.value, (data) ->
      $("#detalleliquidacion_nombreproveedor").val data[0].nombreproveedor 
      $("#detalleliquidacion_proveedor_id").val data[0].id

    false

I want to know if the ajax is empty.

I tried adding this code after the "false" sentence:

campo2 = document.getElementById("detalleliquidacion_proveedor_id").value
alert campo2  if campo2 is ""

But allways return true, because the input field in the form, and this point, still empty.

My enviroment is: rails 3.2.6; ruby 1.9.3p194

How I can know if the ajax return is empty?

Some suggestions will be appreciate.

Regards.

I'm not sure I've correctly understood your question, but it looks like you want to know if the JSON value returned is false or would like to see what is inside of it.

Try something like this

jQuery ->
    jQuery("#detalleliquidacion_nit").change ->
        jQuery('#detalleliquidacion_proveedor_id').val('')
        jQuery('#detalleliquidacion_nombreproveedor').val('')

        jQuery.ajax
            url: "/proveedores/obtenerdatos/" + jQuery('#detalleliquidacion_nit').val()
            success: (data) ->
                if data.length == 0
                    alert 'empty reply from server!'
                try
                    obj = jQuery.parseJSON data
                    console.log obj #useful if you are in chrome, safari, or have firebug
                    if obj[0]?
                        jQuery("#detalleliquidacion_nombreproveedor").val( obj[0].nombreproveedor ) if obj[0].nombreproveedor?
                        jQuery('#detalleliquidacion_proveedor_id').val( obj[0].id ) if obj[0].id?
                catch err
                    alert 'Error parsing: ' + data

        false

using jQuery.ajax allows you more granular control over your returned data than the convenience method jQuery.getJSON

console.log will output to the Development Console and can help you debug. You can also use the more advanced javascript debugging features in Chrome and Safari to set breakpoints and see values of variables at runtime

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