I cannot print success from the below code with the line jQuery.support.cors = true;. Including the line jQuery.support.cors = true; will give a warning message. So how can I avoid that without losing the functionality? My main objective is to call a rest web service that returns JSON data and I have to utilize the JSON data. Please help me with how I can achieve this. Please provide a working sample
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<script>
jQuery.support.cors = true;
$.ajax ({
url: 'http://json-cricket.appspot.com/score.json',
datatype: "json",
success: function (e) {
// Success callback
alert("sucess");
}})
</script>
</body>
</html>
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.
Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
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.
type
//GET or POST, which type of REST OPEATIONdataType
is mispelledcontentType
$.ajax({
type: "POST", //rest Type
dataType: 'jsonp', //mispelled
url: "http://json-cricket.appspot.com/score.json",
async: false,
contentType: "application/json; charset=utf-8",
success: function (msg) {
console.log(msg);
}
});
Updates: While trying to figure out the reason, I think this is the best answer to understand the problem.
Say you're on domain abc.com, and you want to make a request to domain xyz.com. To do so, you need to cross domain boundaries, a no-no in most of browserland.
The one item that bypasses this limitation is tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really DO anything with the results, the script just gets evaluated.
Enter
JSONP
. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle.
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