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);
},
Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.
You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.
parseJSON( json )Returns: String or Number or Object or Array or Booleanversion deprecated: 3.0. Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With