I have a question regarding the following code:
var url = "http://apple.accuweather.com/adcbin/apple/Apple_find_city.asp?location="+escape(obj.extraLocCity)+","+obj.extraLocCountryCode;
$.get(url, function(data) {
var us = $(data).find('CityList').attr('us')*1;
var intl = $(data).find('CityList').attr('intl')*1;
var extra_cities = $(data).find('CityList').attr('extra_cities')*1;
var exist = intl + us + extra_cities;
If "exist" is "0", I would like to make the URL call again using a different "url" variable. Specifically, using "obj.extraLocNeighborhood" in place of "obj.extraLocCity". Any help would be greatly appreciated! Happy to provide more information if need be. Thank you in advance!
You might be looking for something like this
var url1 = "http://apple.accuweather.com/adcbin/apple/Apple_find_city.asp?location="+escape(obj.extraLocCity)+","+obj.extraLocCountryCode;
var url2 = "http://apple.accuweather.com/adcbin/apple/Apple_find_city.asp?location="+escape(obj.extraLocNeighborhood)+","+obj.extraLocCountryCode;
$.get(url1, function(data) {
var us = $(data).find('CityList').attr('us')*1;
var intl = $(data).find('CityList').attr('intl')*1;
var extra_cities = $(data).find('CityList').attr('extra_cities')*1;
var exist = intl + us + extra_cities;
if (!exist) {
$.get(url2, function(data) {
// do something here ....
});
}
);
Why make two calls when you can potentially do it in one? Could you add another parameter to your server handler to accept the neighborhood code in addition to the others and return both results and then handle results all in one shot?
Related
I am using the weatherunderground api, and I would like to access the forecast only for today. I usually use parsed_json[][] until I get the variable I need, but in this case there is an array. Here is my code:
function findWeather() {
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/c531e176f43b999d/forecast/q/CT/Old_Greenwich.json",
dataType : "jsonp",
success : function(parsed_json) {
var forecasts = parsed_json['forecast']['txt_forecast']['forecastday: 0']['fcttext'];
var forecastString = "The weather is" + forecasts + "."
speak(" test" + forecastString);
}
});
});
}
function speak(x) {
var msg = new SpeechSynthesisUtterance(x);
window.speechSynthesis.speak(msg);
}
If you go to the URL, you will see the entire sheet and the info I am trying to access. I've been trying to solve this for a few hours, and can't find any help with google.
Try this:
parsed_json['forecast']['txt_forecast']['forecastday'][0]['fcttext'];
Don't know what you expect the :0 to do, but it won't de-reference the array.
I'm trying to get my array of URL's to run through a JQuery .get function to get the site's source code into one string outside of the function. My code is below.
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var get = $.get(fetch, function(sourcecode) {
sourcecode = fetch;
}
I need the sourcecode variable to be the combination of source code on all of the URLs in the array.
You need to put a variable outside of the function, something like this data variable below and append to it with +=:
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var data = null;
var get = $.get(fetch, function(sourcecode) {
data += fetch;
}
}
Try this like,
var URL = ["http://website.org", "http://anothersite.com"];
var array = $(URL).map(function(fetch) {
var data='';
$.ajax({
url:fetch,
async:false,
success : function(d){
data=d;
}
});
return data;
}).get();
Since you're using jQuery, I suppose that jQuery.each() may be a better way to iterate over the array.
var URL = ["http://website.org", "http://anothersite.com"];
var str = [];
$.each(URL, function(index, fetch) {
$.get(fetch, function(sourcecode) {
str.push(sourcecode); // if you want an array
})
});
str.join(''); // if you want a string
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(i am new. please bear with me.) I have a jquery object that I need to convert back to html to use. What I am doing is using jQuery's get to get the HTML DOM of a local file. The data returned is then made into an object and I perform some tweaks on it (like changing hrefs etc.)
$.get(imagePath + "bloghome.aspx", function (data) {
var pageHtml = $(data);
pageHtml.find('a').each(function () {
var longHref = $(this).attr('href');
var tmp = longHref.lastIndexOf('ID=');
var id = longHref.substring(tmp + 3) + '.htm';
var newHref = imagePath.concat(id);
$(this).attr('href', newHref);
});
});
the object is created in the second line and then i change the hrefs. What I need now is to turn that object back into a string so that I can write it to a file.
I am using PhoneGap but any help would be appreciated as I am stumped
You can do this way using pageHtml[0].outerHTML:
$.get(imagePath + "bloghome.aspx", function (data) {
var pageHtml = $(data);
pageHtml.find('a').each(function () {
var longHref = $(this).attr('href');
var tmp = longHref.lastIndexOf('ID=');
var id = longHref.substring(tmp + 3) + '.htm';
var newHref = imagePath.concat(id);
$(this).attr('href', newHref);
var htmlString = pageHtml[0].outerHTML; //<-- Here
});
});
from http://api.jquery.com/html/
console.log(pageHtml.html());
Can you just do
pageHtml.html();
?
EDIT: Using this will only give you the contents inside the main wrapping element, if you want the entire thing, you can use:
pageHtml[0].outerHTML;
instead.
I am having difficulty setting up a simple html file using javascript to display the results of YQL Query.
I understand how to setup the select statement (example: select title,abstract,url from search.web where query="pizza") in the YQL Console. But I don't know how to display it on the html file?
Can somebody help in explaining how to display the results of that statement?
Code snippets would be appreciated!
BTW, I've read the YQL Docs but they are somewhat complicated.
The only way to retrieve YQL results via client-side JavaScript is JSON-P (or by using an additional proxy). Here's a wrapper for the YQL service:
function YQLQuery(query, callback) {
this.query = query;
this.callback = callback || function(){};
this.fetch = function() {
if (!this.query || !this.callback) {
throw new Error('YQLQuery.fetch(): Parameters may be undefined');
}
var scriptEl = document.createElement('script'),
uid = 'yql' + +new Date(),
encodedQuery = encodeURIComponent(this.query.toLowerCase()),
instance = this;
YQLQuery[uid] = function(json) {
instance.callback(json);
delete YQLQuery[uid];
document.body.removeChild(scriptEl);
};
scriptEl.src = 'http://query.yahooapis.com/v1/public/yql?q='
+ encodedQuery + '&format=json&callback=YQLQuery.' + uid;
document.body.appendChild(scriptEl);
};
}
Usage:
// Construct your query:
var query = "select * from rss where url='somefeed.com' limit 1";
// Define your callback:
var callback = function(data) {
var post = data.query.results.item;
alert(post.title);
};
// Instantiate with the query:
var firstFeedItem = new YQLQuery(query, callback);
// If you're ready then go:
firstFeedItem.fetch(); // Go!!
More info: http://james.padolsey.com/javascript/using-yql-with-jsonp/
Here is a small example for you. I made it using the YQL website:
<html>
<head>
</head>
<body>
<script>
function top_stories(o){
// parse through the output here:
var items = o.query.results.item;
// do whatever you want with the output here:
console.log(items[0].title);
}
</script>
<script src='http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D%22http%3A%2F%2Frss.news.yahoo.com%2Frss%2Ftopstories%22&format=json&diagnostics=false&callback=top_stories'></script>
</body>
</html>
All it does it get the very first news story from Yahoo!'s front page
I've been sitting with this for hours now, and I cant understand why.
q is working. The URL does give me a proper JSON-response. It shows up as objects and arrays and whatnot under the JSON tab under the Net-tab in Firebug and all is fine. I've also tried with other URLs that i know work. Same thing happens.
I have another function elsewhere in my tiny app, wihch works fine, and is pretty much exactly the same thing, just another API and is called from elsewhere. Works fine, and the data variable is filled when it enters the getJSON-function. Here, data never gets filled with anything.
I've had breakpoints on every single line in Firebug, with no result. Nothing happens. It simply reaches the getJSON-line, and then skips to the debugger-statement after the function.
var usedTagCount = 10;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
for(var i = 0; i < usedTagCount; i++) {
tagString += query[i].key + ",";
}
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
debugger; /* It never gets here! */
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
debugger;
return flickrImageData;
}
Example of request URL (q):
http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=20&jsoncallback=?&tags=london,senior,iphone,royal,year,security,project,records,online,after,
I do wonder, since JSONView (the firefox plugin) cannot format it properly, that it isn't really JSON that is returned - the mime-type is text/html. Firebug, however, interprets it as JSON (as i stated above). And all the tag words come from another part of the app.
I think you might need to remove the
nojsoncallback=1
from your searchAPI string.
Flickr uses JSONP to enable cross domain calls. This method requires the JSON to be wrapped in a json callback, the nojsoncallback=1 parameter removes this wrapping.
EDIT: Apparently it works with nojsoncallback=1, I got this piece of code to work for me. What jQuery version are you using? JSONP is only available from 1.2 and up.
This works for me (slight modifications):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
var usedTagCount = 1;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
tagString = query;
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
}
search("cat");
</script>
When I try the url: http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=10&tags=mongo
it returns data, as it should -
try to change the getJSON to an $.ajax() and define a function jsonFlickrApi (data)
with the code you have in you callback function.
If that don't work - please post code to at jsbin.com <- so we can try it live - so much easier to debug.