I'm using the current json structure of this:
jsonp = {"game":[
{"id":"1","gameImage":"qqq.jpg"}
],
"game":[
{"id":"2","gameImage":"hhh.jpg"}
]
}
I'm trying to just get back all the gameImage values. I tried the following but it just won't work. Any ideas?
<html>
<head></head>
<body>
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="javascript" src="gameData.json"></script>
<script>
$(document).ready(function() {
var obj = $.parseJSON(jsonp);
$.each(obj, function() {
alert(this['gameImage']);
});
});
</script>
</body>
</html>
Assuming the first code you show is in the file (incorrectly) named "gameData.json", what you're trying to parse isn't JSON (or JSONP), it's plain JavaScript.
So don't parse it.
Change
var obj = $.parseJSON(jsonp);
to
var obj = jsonp;
Notes :
JSON is a text based data interchange format. Your confusion might come from the many young developers using non-sensical expressions like "JSON object"...
You should avoid naming jsonp a variable holding a plain JavaScript object.
If you prefer to load a JSON file instead of executing a JavaScript file, then
remove the "jsonp = part to make it a real JSON file
remove the script element (as it's not JavaScript anymore)
load the JSON file using ajax
Here's how the JavaScript would be like :
$(document).ready(function() {
$.getJSON("gameData.json", function(obj){
$.each(obj, function() {
alert(this['gameImage']);
});
});
});
or, if you can afford not supporting IE8 :
$(document).ready(function() {
$.getJSON("gameData.json", function(arr){
arr.forEach(function(item){
console.log(item.gameImage); // yes, prefer the console over alert
});
});
});
Related
So, I'm starting to learn JSON handling in javascript, I have an JSON file like this one:
[{"name":"Krzysztof Kowalski", "title":"Na Zdrowie", "author":"Jan Kochanowski"}]
And I'm trying to print it into a website, if I'm not wrong this:
<html>
<head>
<script type="text/javascript" src="data.json"></script>
<script>
function updateUser() {
var configs = JSON.parse(data);
document.getElementById('txt').innerHTML = configs[0].name;
var t = setTimeout(startTime, 500);
}
</script>
</head>
<body onload="updateUser()">
<div id='txt'>
<p>Test text</p>
</div>
</body>
</html>
Should print the "name" field from the first object in JSON, although I get an error like this:
Uncaught ReferenceError: data is not defined
Does anyone know the solution to this problem?
EDIT: changed
document.getElementById('txt').innerHTML = data[0].name;
to
document.getElementById('txt').innerHTML = configs[0].name;
For it to work, your JSON file must rather look like this:
data = '[{"name":"Krzysztof Kowalski", "title":"Na Zdrowie", "author":"Jan Kochanowski"}]'
If you prefer to go up with a conventional JSON file, http://api.jquery.com/jQuery.getJSON/ should help in that more normal approach.
I'm new to Javascript and jQuery and I want to create a function to convert JSON to XML. I searched through the internet and the only one I got is http://code.google.com/p/x2js/
Below is the function I wrote and it does not work.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='https://code.jquery.com/jquery-git.js'></script>
<script type='text/javascript' src="x2js-v1.1.5/xml2json.min.js"></script>
<script type='text/javascript'>
$(window).load(function(){
var json = null;
var x2js=newX2JS();
$.ajax({
'async': false,
'global': false,
'url': "sample.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
function convertJsonToXml(){
var xmlDOM=x2js.json2xml(json);}
});
</script>
</head>
</html>
The json file I want to read is "sample.json". It is at the same directory as the html file.
Someone please help me to make this work.
This is the error I'm having in the console
TypeError: url.indexOf is not a function jquery-git.js:9217:8
The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.
jQuery is trying to use the Ajax load method instead of binding a load event handler. The function you are passing isn't a URL string so it errors.
You want:
$(window).on('load', function(){
instead.
Try if this works. In this way you will be able to locate the problem.
$(window).load(function(){
var json = {'a': 'b'};
var x2js=new X2JS().json2xml(json);
}
I'm trying to get JSON array from my php-script. Following is my Jquery code written in my jsp file-
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://example.com/root_dir/test_json.php', function(data)
{
alert(data);
});
});
but, above code showing only outer alert (i.e. alert("Inside Ready");) and not showing inner alert (i.e. alert(data); ). I'm getting expected json when I hit URL in browser. So definitly there is no problem in URL and php-script.
following is test_json.php
<?php
//Create an array
$json_response = array();
$row_array['label'] = 'A';
$row_array['value'] = $row['0 to 2'];
$row_array['color'] = '#FA2020';
array_push($json_response,$row_array);
$row_array['label'] = 'B';
$row_array['value'] = $row['2 to 3'];
$row_array['color'] = '#2BD95A';
array_push($json_response,$row_array);
$row_array['label'] = 'C';
$row_array['value'] = $row['above 3'];
$row_array['color'] = '#F7F739';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
Getting following json when I hit URL in browser-
[{"label":"A","value":"19","color":"#FA2020"},{"label":"B","value":"1","color":"#2BD95A"},{"label":"C","value":"2","color":"#F7F739"}]
I'm using jquery-1.10.2.js. Thank You..!
Try This one...Hope so it is useful to you
$(document).ready(function()
{
$.ajax({
type:'POST',
url:'http://example.com/root_dir/test_json.php',
dataType:'JSON',
data:{
},
success:function(data1){
alert(data)
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("error");
}
});
});
Your code seems to be working fine -
I just created a test page with your code and it works -
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://<<CHANGE SERVER NAME>>/zz-test/get_json.php', function(data)
{
alert(data);
});
});
</script>
</head>
<body>
</body>
</html>
Your jQuery and PHP code looks fine so, in my experience, it is usually an error caused by calling your PHP script from a different domain (i.e.: file:///). If you can access your browser's console, you should be able to see if this is in fact the error causing the data not to be displayed.
One solution for this is to add at the top of your PHP code:header('Access-Control-Allow-Origin: *');. There are however some security concerns with this, so it should not be used permanently.
Alternatively, you could upload all your HTML, CSS, JS, jQuery, etc. code to the web server hosting the PHP file, which is a far better option.
Finally, if the option above is not possible you could use JSON-P (although this does not work with POST requests), there is a question about this at Simple jQuery, PHP and JSONP example?
Here is my code for a page...
<html>
<head>
<script src="jquery-1.7.2.js"></script>
</head>
<body>
<script>
var url = "https://natiweb-natiweb.rhcloud.com/game.php";
$.getJSON(url,function(data){
$.each(data,function(i,user){
alert("inside json");
alert(user.appname);
});
}
);
</script>
</body>
</html>
I'm unable to get data from server.... alert does not gets popped up
it works fine if I write the script code inside a js file. but i need to dynamically populate a page, hence I need to write this query inside body.
I added alert inside the json function. even that is not getting popped. I think json isn't getting executed
Try This.....
var url = "https://natiweb-natiweb.rhcloud.com/game.php";
$.getJSON(url,function(data){
$.each(data,function(i,user){
alert(user.appname[i]);
});
}
);
try this one,Becoz you are getting array in that array your json is present
alert(user[0].appname);
Try to auto-execute your code, that's what the example says on the jquery doc.
<script>
(function() {
var url = "https://natiweb-natiweb.rhcloud.com/game.php";
$.getJSON(url,function(data){
$.each(data,function(i,user){
alert("inside json");
alert(user.appname);
});
}
);
})();
</script>
I'm trying to download some data using pure javascript/html from cross-domain, dropbox to be specific.
<html>
<head>
</head>
<body>
<div id = 'twitterFeed'></div>
<script>
function myCallback(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
document.getElementById('twitterFeed').innerHTML = text;
}
</script>
<script type="text/javascript" src="http://dl.dropbox.com/u/6438697/padraicb.json?count=10&callback=myCallback"></script>
</body>
for some reason, the json is not loading. however the json loads correctly when I make the url "http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback" instead. I got this example from here
Can anybody explain why dropbox doesn't work?
thanks!
UPDATE:
<script type=text/javascript>
function myCallback(dataWeGotViaJsonp){
alert(dataWeGotViaJsonp);
}
</script>
<script type="text/javascript" src="http://dl.dropbox.com/u/6438697/test2?&callback=myCallback"></script>
returns either [object object] or undefined... something is still wrong? the contents of test.json is myCallback( {"your":"json"} );
You can't just add the word 'callback' to your URL and expect Dropbox to wrap it for JSONP. You put a JSON file on your Dropbox and shared it publicly, but Dropbox isn't a dynamic server. You need a scriptable environment to take the callback parameter value and wrap it around the JSON in order to make it "JSONP".
The reason the Twitter URL works is that their API is configured to take the callback parameter as a sign that the client is expecting JSONP, which is really just a fancy term for "a JavaScript object literal wrapped in a callback function". You tell twitter what that function will be called, and they'll return a file that the browser will execute as a script, passing the object as a parameter to your callback function.
If you don't need the JSONP callback function name to be dynamic AND you need to use Dropbox, just wrap the JSON yourself. All you need to do is edit the file, and prepend valid JSON with the name of the function, and append it with the close paren.
ie,
myCallback( {"your":"json"} );
It is possible to use Google Apps Script as a proxy for hosting sites that do not support jsonp. There is writeup on how to do it here http://ramblings.mcpher.com/Home/excelquirks/jsonp