How Can I Get Jquery .get To Return Json Data?
Solution 1:
May I suggest to use something like this:
$.ajax({
type: 'GET',
url: myURL,
data: yourDAta,
dataType: 'jsonp',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('Error loading ');
}
});
Note the usage of jsonp
over json
Solution 2:
just add json as the third parameter, the data passed to the callback will be an object representation of the received json string
this should work,
var teamId = 883455;
var myUrl = "https://apps-internal.attributor.com/guardianapi/service/csadminservice/csteams/" + teamId + "?view=PUBLISHERS_FOR_TEAM";
$.get(myUrl, function(data){
//data here will be object, should not used directly
$("#pub").html(data);
alert("load was performed");
}, 'json');
if you are on different domain, you could setup a server side script to grab that data, say it is php file called api.php
<?php$teamId = $_GET['teamId'];
//php.ini should allow url fopen$response = file_get_contents("https://apps-internal.attributor.com/guardianapi/service/csadminservice/csteams/". $teamId ."?view=PUBLISHERS_FOR_TEAM");
echo$response;
?>
and call it in your js file
var teamId = 883455;
var myUrl = "path/to/api.php?teamId="+teamId;
$.get(myUrl, function(data){
//data here will be object, should not used directlyconsole.log(data);
}, 'json');
Solution 3:
Try using the getJSON() method instead if you're only interesting in getting back a JSON response.
The .get, .load, .getJSON are all just extensions that use the .ajax method underneath, if you can't get the extension method working it sometimes helps to just use straight .ajax()
Essentially the getJSON() method is just this:
$.ajax({dataType:"json",url:url,data:data,success:success});
Note the explicit use of the dataType: "json".
Since this looks like a cross-domain call you will need to use something like jsonp (JSON with padding) or CORS (Cross-origin resource sharing) if your endpoint supports it. If jsonp is supported by your endpoint you can set the dataType: "jsonp" but it needs to be explicitly supported by the server see this post for more details on jsonp.
Note: your server API must support jsonp or CORS for this to work.
Post a Comment for "How Can I Get Jquery .get To Return Json Data?"