Reputation: 5532
I have this piece of code:
$.ajax({
url: '/piece.json',
type: "GET",
dataType: "json",
success: function (data) {
alert(data);
}
});
I am on a rail3 app, when I type "/piece.json" I get on my browser what I want. But I cant make it alert using Javascript! Why this happens?
Solved, had to use this:
complete: function (data_response) {
alert(data_response.responseText);
},
Upvotes: 16
Views: 98021
Reputation: 858
This worked for me:
$.getJSON( "example.json", function(data) {
console.log( "success" );
}).done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
Replace example.json, with the url or path of your json file. Note the use of $.getJSON vs $get . Here's my reference: http://api.jquery.com/jquery.getjson/
Upvotes: 8
Reputation: 303136
Presumably you don't have a working route for /piece.json
. Use the Developer Tools in your browser and log from the rails app to see what is going on with the XHR request.
(Look at the http response in the browser.)
Note that you can more simply use:
$.get('/piece.json',function(data){
// data is a JS object parsed from a JSON response
},'json');
Upvotes: 3
Reputation: 5929
try to use complete
callback instead of success
. I don't why but success
callback doesn't fires even if all data and response are correct. Looks like some kind of bug
Upvotes: 2
Reputation: 2444
Try changing the datatype to JSONP. It's usually to overcome the Same Origin Policy but may work in your case.
$.ajax({
url: '/piece.json',
type: "GET",
dataType: "jsonp",
success: function (data) {
alert(data);
}
});
Upvotes: 3
Reputation: 2291
Add this and see what is returned
error: function (error) {
alert(JSON.stringify(error));
}
Upvotes: 1
Reputation: 5156
It's possible that piece.json
doesn't returns valid JSON so jQuery discards it. Try to change dataType: "json"
to dataType: "html"
and see if the alert(data)
shows the output. If the alert shows your data then there's a syntax error in the json object.
Upvotes: 6