Cannot get json response using $ .getJSON

I am currently developing a Ruby on rails 3 application.

My server manager function displays the json object as the answer:

class DaysController < BaseController
   ...
   def the_days
     ...
     render :json => days
   end
end

In my javascript, I use the following code to get a json response from the server (which is from a function the_dayin the controller)

$.getJSON(  
             url,  
             {emp_id: emp_id},
             function(data) {
                     var result = data.response;
                     alert(result) 
                     alert(data)
                 },
                 "json"
        );

I use firefox browswer and verified with Firebug , in Firebug Net-> XHR, I see that the Get request is successful, and there is a "days" answer. This request and response are successful.

But I did not see the two warning windows defined in the function above $.getJSON, why? Why can not I get the answer " days " in the function $.getJSON?

----------------- ------------------ Edited

I edited my code:

$.ajax({
            url: myURL,

            type: 'GET',

            data: {
                emp_id: emp_id
            },

            dataType: "json",

            success: function(data) {
                alert("hi");
                alert(data)
            }
        });

, success: function(data)

+3
5

data null, , , , .

//, .

, Chrome, --disable-web-security.


: data - , dat - .

:

alert( dat );

, data, data AJAX.

+2

, , data response. data. days.

+1

, , , .

, - . , , , . ...

$.getJSON(  
             url,  
             {emp_id: emp_id},
             function(data) {
                     alert('hi')  // add this
                     var result = data.response;
                     alert('bye') // add maybe even this
                     alert(result) 
                     alert(data)
                 },
                 "json"
        );

, , , .

: ,

$.ajax({
        url: 'users/check_username',
        type: 'GET',
        data: {
          username: username
        },
        dataType: "json",
        success: function(user_exists) {
          alert(user_exists)      // CHANGE THIS PART
        }
      });
0

, . Firebug Content Type application/json, , JQuery.

You can try changing the datatypehtml in your ajax call to see if it works with it alert, but that doesn't help with json parsing.

0
source

ALL, finally, I understood the main reason. The reason is simply because of the " Invalid json data " returned by the server. This is in the rails controller function ' def the_days':

render :json => days

should be changed to

render :json => days.to_json

Then everything works smoothly :) Thanks to everyone, anything!

0
source

Source: https://habr.com/ru/post/1791838/


All Articles