I have this small code example:
<script type="text/javascript">
var texts = [{key:'key_1', value:'value_1'},
{key:'key_2', value:'value_2'},
{key:'key_3', value:'value_3'}];
</script>
I use a json array directly in my xhtml page by using the script tag. The json array "texts" is used by an another java script function in my xhtml page, but that is not important at the moment.
How can a extract this json array into an external file? Which library it must be used?
EDIT:
I use a java maven project and that should be include my external json file!
I tried this code but it doesn´t work:
<script type="text/javascript">
var placeholderTexts = himjQuery(document).getJSON('placeholder.json');
</script>
You can use each loop in jQuery
Just try this
$.each(texts, function(key, value) { }
please try the below.
var arraysel;
var json = { };
for(var i = 0, l = arraysel.length; i < l; i++) {
json[arraysel= [i].id] = arraysel= [i].value;
}
After reading many times your question, I think what you want is this:
Create a .js file, for example data.js, with your data... which is not a JSON-serialized object, but a real literal. Use pure JSON notation if you want.
var DATA = {"a":1, "b":2};
Import that "script" wherever you want to use your data.
<script type="text/javascript" src="./data.js></script>
Use this data from any place in your JS code, for instance:
console.log(DATA.a);
Please get JSON data from AJAX and evaluate response and store in variable
<script>
var placeholderTexts = new Object();
$(function(){
$.get('placeholder.json', function(data){
try{
placeholderTexts = jQuery.parseJSON(data);
console.log(placeholderTexts)
}catch(e){
alert(e.toString());
}
});
});
</script>
Related
I'd like to get data from the following site: https://www.portaldefinancas.com/framecdi.htm
I'm using google sheets with IMPORTXML function. I learn a little bit about xpath and I believe that my problem isn't syntax.
The problem is that it seems this website do not want that people get data from it.
The piece of code I need from the source code is following:
... </fieldset><div class="column50"><script src="js-gen-ctb/tb-tb.js"></script>
Taxas CDI - Mensal - Anual - Acumulada - 2021
<script src="js-tx-ctb/th-cdib.js"></script>
<script src="js-tx/cdib-2021.js"></script> ...
As you can see, at the exact point the data should appear there is a lot of scripts. When I access these scripts the only thing that is inside of them is a document.write piece of code, like this:
document.write(""),document.write('<table cellspacing="1" cellpadding="3" id="tb"><caption><p class="cp">');
The only function of these scripts is to group the source code in many parts in different files.
In this way, I can't access data because the function IMPORTXML return #NA error since the data is outside of source code.
Is there any way to I get data using the function IMPORTXML in this case? how can I access the data inside a .js file with this formula?
Thanks
Data can be retrieved by parsing the contents of html table in js files as follows
function getTaxas(url) {
var source = UrlFetchApp.fetch(url).getContentText()
source = source.split('document')[2]
var table = '<table><tr><td' + source.match(/(?<=td).*(?=td)/g) + 'td></tr></table>'
var doc = XmlService.parse(table);
var rows = doc.getDescendants().filter(function(c) {
var element = c.asElement();
return element && element.getName() == "tr";
});
var data = rows.slice(0).map(function(row) {
return row.getChildren("td").map(function(cell) {
return cell.getValue();
});
});
return data;
}
https://docs.google.com/spreadsheets/d/18yhDYr91ORrofV20FMWYmYnwwnGK0QaQguG9uLdP5co/copy
I am printing some php data into a field on my page. The data is json_encoded by the backend.
Now i want to retrieve this information and turn it into a javascript object...
$(document).ready(function(){
$('.trigger-info-change').click(function(){
var rel = $(this).attr('rel');
var td_id = 'info-'+rel;
var data = $('#'+td_id).html();
console.log(data);
});
});
now data is correctly console logging my "object" like this:
{"data":{"id":"1","data1":"1","data2":"2"},{"id":"2","data1":"3","data2":"4"}}
Now the question is how do i turn this html into a actual javascript object... I've tried to use jQuery.parseHtml, and some other things google advised but no luck... would i need a script or is there something like that out there?
Thanks in advance!
If you want use Jquery:
var json = $.parseJSON(data)
Or
var obj = JSON.parse(data);
I think this better to print out JSON String in javascipt.
<script>
var data = <?php echo $json ?>;
</script>
Which makes :
<script>
var data = {"data":{"id":"1","data1":"1","data2":"2"},{"id":"2","data1":"3","data2":"4"}};
</script>
But if you insist on your way, use JSON.parse(jsonString).
How would one load a javascript structure (object or array) from a file in Cocos2d-X 3.
My res/test.json:
{
version:"1.0",
data:"this is some data."
}
I'm able to load the file content like so:
var data = fileUtil.getStringFromFile('res/test.json');
cc.log(data);
What is the best way to load the javascript structure from the string? Is there a function in cocos2d-x to do this directly?
The "standard" JSON.parse works:
var fileUtil = cc.FileUtils.getInstance();
var data = fileUtil.getStringFromFile('res/test.json');
var jData = JSON.parse(data);
But note all attribute names must be passed in quotes, otherwise the parser will fail. res/test.json must then look like this:
{
"version":"1.0",
"data":"this is some data."
}
This seems like a simple problem but I have a coder's mental block:
The concept:
I type a URL, i.e - www.mysite.com/getStuff?name=Jerry&occupation=Engineer&Id=12345
and instead of getting back a webpage or something I want to get back a json object so that I can parse on a different page.
The catch:
I can certainly accomplish this by calling a MVC controller with those parameters and returning a json object. However, Let's say I need to create this json object inside a js file that takes those parameters' values from the URL and I get my json back as the result.
The questions
Can I pass parameters to a js file and return a json object? Or
Can I call a js file from a controller and pass it these parameters to and retrieve a json object?
Do I even need to call a controller via a URL, or can I just call a js file giving it parameters from a URL and then returning the json?
What is the proper/best way of handling this scenario, with MVC, js, jquery...anything??
Thanks a lot guys!
You have a couple of options
1) Generate the json in javascript
To do this you will need to create a simple page which includes a javascript JSON encoder (such as https://github.com/douglascrockford/JSON-js). This would be hosted at "/getStuff/index.html" and would be called by typing "www.mysite.com/getStuff/?arg=val..." For example:
<html>
<head>
<script src="json.js" type="text/javascript"></script>
<script type="text/javascript">
//this function will take the window.location.search string of ?name=val and
//create an object like {'name':'val'}
var parseUrl = function(urlParams) {
var retObj = {};
var urlParameters = null;
if (!urlParams || urlParams.length == 0) {return retObj}
if (urlParams.charAt(0) == '?') {
urlParameters = urlParams.substring(1);
}else {
urlParameters = urlParams;
}
if (urlParameters.length == 0) {return retObj}
var parameterPairs = urlParameters.split('&');
var x;
for (x in parameterPairs) {
var parameterPair = parameterPairs[x];
parameterPair = parameterPair.split('=');
retObj[parameterPair[0]] = parameterPair[1];
}
return retObj;
};
var createJson = function(){
var params = parseUrl(window.location.search);
//do work here
var retObj = {}; //suppose this is the result of the work
document.print(JSON.stringify(retObj)); //use the included JSON encoder
};
</script>
</head>
<body onload="createJson();">
</body>
</html>
2) Use an MVC framework
Every MVC framework in existance will give you access to the search params used in the page request. Some will require you to provide them in /function/arg1/arg2 style (so /getStuff/jerry/engineer/12345, in your case). Others use a more traditional /function/?argName=argVal... approach. Once you have the arguments, it is a trivial matter to write them to the page in JSON format (http://php.net/manual/en/book.json.php).
Decisions, Decisions
Personally, I would use the MVC method, as it requires the least running around to get the JSON you want. However, unless you are familiar with an MVC framework (such as cake) you will probably find the process of getting up and running to be a bit arduous - these frameworks are designed for serving page content and getting them to serve up JSON is not always clearly documented.
Use jquery to parse the URL by inserting this into a <script> tag before creating the json object. from link from LekisS
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its nam
var byName = $.getUrlVar('name');
In a separate script tag create your json object. You will need to include the Json2.js plugin to convert objects to JSON. So include this script also before the JSON object creation.
Once you have the appropriate scripts and variables you can create a json object using those parameters as needed by calling them as shown at the bottom of the example using jquery. You can also look up which JSON conversion (i.e, to string or object) you want from the Json2.js script file.
Now we have everything inside a bunch of scripts but where do we get json object through URL calling?
So the answer is simple:
Create a simple html page with these scripts where the last script finally creates and returns the json. Upload to server and use URL parameters like
www.mysite.com/getStuff?para1=value¶2=value2 to get the json object.
This is format of JSON data: [{"options":"smart_exp"},{"options":"user_int"},{"options":"blahblah"}] that I receive through getjson from server. I need to append json with user input. I am trying to do it in this way: 1st convert it into javascript object, append it with user input, again convert to json object & send it back to server for database update. I have converted json to javaScript object using eval(). Now not able to manipulate javascript object. If I convert javascript object back to json object, it displays correctly all data that was sent from server.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
<body>
<form name="index">
<p><input type = "text" id = "txt" name = "txt"></input></p>
<p><input type = "button" id = "send" name = "send" value = "send"
onClick="ADDLISTITEM();"></input></p>
<select name="user_spec" id="user_spec" />
</form>
<script>
function ADDLISTITEM()
{// this script suffers from errors on eval/JSON.parse methods
alert (json.length);//outputs corrcet with eval
tring = JSON.stringify(json);//outputs corrcet with eval
alert(jsonString);//outputs corrcet with eval
alert(json.options[0]);//no output
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script src="http://www.json.org/json2.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = eval(jsonData);
//json = JSON.parse(jsonData);/*error if uncomment:"IMPORTANT: Remove this line from
json2.js before deployment"*/
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});});
});
</script>
</body>
</html>
In jQuery, $.getJSON()'s callback gets called with parsed JSON data; just use it.
$.getJSON("*.php", function(data) {
$.each(data, function() { alert(this.options); });
);
should give you an alert for every {"options": "xyzzy"} object in the array.
EDIT after OP edited their post:
Your edit clarifies things a little: You won't get any data back -- and it will be completely silent, too, as I found out -- if you violate the same origin policy.
Basically (with exceptions (preflight checks, etc)), you can only access URLs on the exact same domain via AJAX. If your HTML file is a static file served locally, it can not access http://127.0.0.1/; if your file is http://foo.baz.quux.org/, you can't simply AJAX into http://mordor.baz.quux.org .
I don't think the problem here has anything to do with eval/parse etc or the same origin policy. Your json is an array of objects each containing a member named options. Therefore you cannot do json.options[0], you have to do json[0].options.
var json = [{"options":"smart_exp"}, {"options":"user_int"}, {"options":"blahblah"}]
for (var i = 0; i < json.length; i++){
alert(json[i].options)
}