I have xml respnse from ajax call. I want to iterate it.
Below is my xml ouput in SoaUi.
I want output response as below:
50 Water St Oakland USA
101 Emerall New York USA
Sea Point CA USA
Please help me to write response in jQuery.
EDIT:
This is my response in xml:
<ns3:Row>
<ns3:AddressLine1>50 Water St</ns3:AddressLine1>
<ns3:City>Oakland</ns3:City>
<ns3:Country>USA</ns3:Country>
</ns3:Row>
<ns3:Row>
<ns3:AddressLine1>101 Emerall</ns3:AddressLine1>
<ns3:City>New York</ns3:City>
<ns3:Country>USA</ns3:Country>
</ns3:Row>
<ns3:Row>
<ns3:AddressLine1>Sea Point</ns3:AddressLine1>
<ns3:City>CA</ns3:City>
<ns3:Country>USA</ns3:Country>
</ns3:Row>
You can get the information required looping through the elements and storing the information in a string or whatever you find fit.
One solution (mixing jquery and plain javascript) could be as follows:
$(f).each(function (ind, el) {
var line = '';
$(el).children().each(function (ind, nod) {
line += nod.childNodes[0].nodeValue + ' ';
});
console.log(line.slice(0, -1));
});
the variable 'f' contains the XML string retrieved from the server.
You can test it in this fiddle (open the developer's console to see the result printed there).
Hope it helps.
Solution is here.
var geoCompAddress;
$(data).find('ns3\\:Row').each(function() {
geoCompAddress = $(this).find('ns3\\:AddressLine1').text()+ ',' + $(this).find('ns3\\:City').text()+ ',' + $(this).find('ns3\\:Country').text() ;
});
Related
like so
► add language identifier to highlight code
```python
def function(foo):
print(foo)
► put returns between paragraphs
► for linebreak add 2 spaces at end
► italic or bold
► indent code by 4 spaces
► backtick escapes like _so_
► quote by placing > at start of line
► to make links (use https whenever possible)
https://example.com
example
example
As mentioned by #Pointy there are multiple syntax errors in your code (when accessing the obj array).
But the reason it wouldn't work even after you fix these syntax errors is that the result of your API call is a string and you need to parse it using JSON.parse().
$.get('https://raw.githubusercontent.com/danielhoset27/test1/master/C2RReleaseData.json', function(obj) {
// Parse the received json
const result = JSON.parse(obj);
// Fix the syntax errors
document.writeln(result[0].FFN + " : " + result[0].AvailableBuild);
// Add a line break
document.write('<br />')
// Fix the syntax errors again
document.writeln(result[1].FFN + " : " + result[1].AvailableBuild);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Also consider using Fetch API is your targeted browsers support it.
const appendItem = item => document.body.innerHTML += `<p>${item.FFN} : ${item.AvailableBuild}</p>`;
fetch('https://raw.githubusercontent.com/danielhoset27/test1/master/C2RReleaseData.json').then(response => {
response.json().then(result => {
appendItem(result[0]);
appendItem(result[1]);
});
});
Try This code
$(document).ready(function(){
var url = 'https://raw.githubusercontent.com/danielhoset27/test1/master/C2RReleaseData.json';
$.getJSON(url, function( data ) {
for(var i in data){
console.log(data[i].FFN + " : " + data[i].AvailableBuild)
}
});
});
I'm using highlight.js to display some JSON I'm receiving from a pubnub subscription. It is coloring the text but it is not adding line breaks as expected (via their demos). Also, a couple places in the documentation give the impression that the library generates new lines. See the useBR option here.
Here is my current code (I've tried a few different things):
pubnub.subscribe({
channel : 'TEST',
message : function(m){
console.log(m);
var hlt = hljs.highlight('json',m);
$('#jsonOutput').html("<pre>" + hlt.value + "</pre>");
}
});
And here is what the DOM looks like:
But here is the output:
How can I get line breaks? I want it to look similar to this:
{
"id":"TESTWIDGET1",
"value":371,
"timestamp":"2016-08-31T11:39:57.8733485-05:00"
}
fiddle: https://jsfiddle.net/vgfnod58/
You don't have any line-breaks in your code. The highlight function will only apply the formatting options, when the json-string was formatted. You string is only one single line. So, you will have to bring it in the right format first and then you can highlight it:
function print_r(object,html){
if(html) return '<pre>' + JSON.stringify(object, null, 4) + '</pre>';
else return JSON.stringify(object, null, 4);
}
var m = {"id":"TESTWIDGET1","value":351,"timestamp":"2016-08-31T12:03:24.3403952-05:00"};
var hlt = hljs.highlight('json',print_r(m));
$('#codehere').html(hlt.value);
Please be aware that I changed the var m from string to object (just remove the sourrunding ').
A working fiddle: https://jsfiddle.net/WalterIT/vgfnod58/2/
You should be able to substitute using <div> element with css white-space set to pre for <pre> element
Edit, Updated
Alternative approach inserting non-breaking space and newline characters before and after highlighted <span> elements
var m = '{"id":"TESTWIDGET1","value":351,"timestamp":"2016-08-31T12:03:24.3403952-05:00"}';
// hljs.configure({useBR: true});
var hlt = hljs.highlight('json',m);
$('#codehere').html(hlt.value)
$('#codehere span').each(function(i) {
if (i % 2 === 0)
$(this).before("\n ");
if (i === $('#codehere span').length -1)
$(this).after("\n")
});
jsfiddle https://jsfiddle.net/vgfnod58/3/
I have a web page in which contents are loaded dynamically from json. Now i need to find the texts like so2,co2,h2o after the page gets loaded and have to apply subscript for those texts. Is it possible to do this?? If yes please let me know the more efficient way of achieving it.
for example :
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is"};
in the above json i need to change CO2,H2O and e in CTUe as subscript. how to achieve this??
Take a look at this JSfiddle which shows two approaches:
HTML-based using the <sub> tag
Pure Javascript-based by replacing the matched number with the subscript equivalent in unicode:
http://jsfiddle.net/7gzbjxz3/
var json = { chemA: "CO2", chemB: "H2O" };
var jsonTxt = JSON.stringify(json).replace(/(\d)+/g, function (x){
return String.fromCharCode(8320 + parseInt(x));
});
Option 2 has the advantage of being more portable since you're actually replacing the character. I.e., you can copy and paste the text into say notepad and still see the subscripts there.
The JSFiddle shows both approaches. Not sure why the magic number is 8320 when I was expecting it to be 2080...
So you are generating DOM element as per JSON data you are getting. So before displaying it to DOM you can check if that JSON data contains so2,co2,h2o and if it is then replace that with <sub> tag.
For ex:
var text = 'CO2';
text.replace(/(\d+)/g, "<sub>" + "$1" + "</sub>") ;
And this will returns something like this: "CO2".
As per JSON provided by you:
// Only working for integer right now
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is"};
$.each(json, function(index, value) {
json[index] = value.replace(/(\d+)/g, "<sub>" + "$1" + "</sub>");
});
console.log(json);
Hope this will helps!
To do this, I would create a prototype function extending String and name it .toSub(). Then, when you create your html from your json, call .toSub() on any value that might contain text that should be in subscript:
// here is the main function
String.prototype.toSub = function() {
var str=this;
var subs = [
['CO2','CO<sub>2</sub>'],
['H2O','H<sub>2O</sub>'],
['CTUe','CO<sub>e</sub>'] // add more here as needed.
];
for(var i=0;i<subs.length;i++){
var chk = subs[i][0];
var rep = subs[i][1];
var pattern = new RegExp('^'+chk+'([ .?!])|( )'+chk+'([ .?!])|( )'+chk+'[ .?!]?$','ig'); // makes a regex like this: /^CO2([ .?!])|( )CO2([ .?!])|( )CO2[ .?!]?$/gi using the surrent sub
// the "empty" capture groups above may seem pointless but they are not
// they allow you to capture the spaces easily so you dont have to deal with them some other way
rep = '$2$4'+rep+'$1$3'; // the $1 etc here are accessing the capture groups from the regex above
str = str.replace(pattern,rep);
}
return str;
};
// below is just for the demo
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is", chemD: "CO2 is awesome", chemE: "I like H2O!", chemF: "what is H2O?", chemG: "I have H2O. Do you?"};
$.each(json, function(k, v) {
$('#result').append('Key '+k+' = '+v.toSub()+'<br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Note:
Anytime you do something like this with regex, you run the chance of unintentionally matching and converting some unwanted bit of text. However, this approach will have far fewer edge cases than searching and replacing text in your whole document as it is much more targeted.
I've recently come across the term arbitrary data/ arbitrary json and i can't seem to understand what exactly is it and/or find any documentation on it. I know that JSON is a format for sending data over the internet, so how exactly can a format be arbitrary?
EDIT::
//more code
var buildItem = function(item) {
var title = item.name,
args = [],
output = '<li>';
if (item.type == 'method' || !item.type) {
if (item.signatures[0].params) {
$.each(item.signatures[0].params, function(index, val) {
args.push(val.name);
});
}
title = (/^jQuery|deferred/).test(title) ? title : '.' + title;
title += '(' + args.join(', ') + ')';
} else if (item.type == 'selector') {
title += ' selector';
}
output += '<h3>' + title + '</h3>';
output += '<div>' + item.desc + '</div>';
output += '</li>';
return output;
};
//more code
in the example code above, i am told that the .params is arbitrary data from a JSON request [for the jQuery API documentation].
What then is arbitrary data?
Would really appreciate any answers and/or clarifications.
jsFiddle: http://jsfiddle.net/QPR4Z/2/
Thanks!
arbitrary |ˈärbiˌtrerē|
adjective
based on random choice or personal whim, rather than any reason or
system: his mealtimes were entirely arbitrary.
Mathematics: (of a constant or other quantity) of unspecified value.
It just means there could be any value in there. This is opposed to a specification that says something like "this array always contains X, Y and Z". Arbitrary values in contrast say "we're sending you something in this array, but we can't really tell you in advance what exactly that is." If you're told that you can send arbitrary data yourself, it means you can send anything you want, it doesn't have to follow any particular format.
Note that this is all about the data contained in the JSON format, not about the JSON format itself.
It means "Some organisation of the data structure (including names of properties) that was just made up by some person" rather than being an established standard.
The data structure is arbitrary. It is expressed in the JSON standard (which isn't).
Update: I tried a version of the script without the "beforeContentUpdate" part, and this script returns the following JSON
{"COLUMNS":["TNAME","TBRIEF","GAMEID","TITLEID","RDATE","GNAME","PABBR","PNAME","RSCORE","RNAME"],
"DATA":[["Dark Void","Ancient gods known as 'The Watchers,' once banished from our world by superhuman Adepts, have returned with a vengeance.",254,54,"January, 19 2010 00:00:00","Action & Adventure","X360","Xbox 360",3.3,"14 Anos"]]}
Using the script that includes "beforeContentUpdate," however, returns nothing. I used Firebug to see the contents of the div generated by the tooltip, and it's blank!
Hello, I'm wondering if anyone can help me with a syntax error in line 14 of this code:
The debugger says missing ) in parenthetical on var json = eval('(' + content + ')');
// Tooltips for index.cfm
$(document).ready(function()
{
$('#catalog a[href]').each(function()
{
$(this).qtip( {
content: {
url: 'components/viewgames.cfc?method=fGameDetails',
data: { gameID: $(this).attr('href').match(/gameID=([0-9]+)$/)[1] },
method: 'get'
},
api: {
beforeContentUpdate: function(content) {
var json = eval('(' + content + ')');
content = $('<div />').append(
$('<h1 />', {
html: json.TNAME
}));
return content;
}
},
});
});
});
You forgetting a
+
Should be:
var json = eval('(' + content + ')');
the best for this is www.jslint.com
i'd copied and paste your code and show me this:
Problem at line 21 character 10: Extra
comma.
},
Make sure you JSON has no extra characters, the JSON must be valid. Check how the content returns with a plain alert so nothing will change the string.
Also, consider using parseJSON from jQuery instead of eval. Quote:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
This turned out to be another case where the ColdFusion debugger, when request debugging output is turned on, causes an ajax error. This is one big "gotcha" we need to remember when working with ColdFusion with debugging enabled. It breaks down ajax.