image from ajax request loads in codepen but not local environment - javascript

I'm trying to use a weather api for a basic website and I'd like to use the icons too. The request works in both environments, but in my local environment I get an error for the icon
GET file://cdn.apixu.com/weather/64x64/night/116.png net::ERR_FILE_NOT_FOUND
I thought it was related to https but probably not since it's only the image that won't load.
const key = 'b7e1e81e6228412cbfe203819180104';
const url = `https://api.apixu.com/v1/current.json?key=${key}&q=auto:ip`
const main = document.getElementById('main');
$.getJSON( url, function(json) {
const loc = json.location;
const cur = json.current;
const condition = {text: cur.condition.text, icon: cur.condition.icon}
main.innerHTML = `<img src = ${condition.icon}><div>${condition.text}</div>`
}
so ${cur.condition.text} will display "partly cloudy" but the icon does not display. Any advice?
update: seems to be working fine with live-server.

It may be because the Cross-Origin Request Policy (CORS) may not allow it. Please make sure that you are allowed to access those resources.
https://enable-cors.org/ to read up more about CORS.
Secondly,
<img src = ${condition.icon}>
should be
<img src="${condition.icon}">
You are forgetting the quotation marks.
https://www.w3schools.com/tags/tag_img.asp - Read more on image tags.
Additionally use the code below:
Also add http: to image src like <img src=http:${condition.icon}>.
const key = 'b7e1e81e6228412cbfe203819180104';
const url = `https://api.apixu.com/v1/current.json?key=${key}&q=auto:ip`
const main = document.getElementById('main');
$.getJSON(url, function(json) {
const loc = json.location;
const cur = json.current;
const condition = {
text: cur.condition.text,
icon: cur.condition.icon
}
main.innerHTML = `<img src="http:${condition.icon}"><div>${condition.text}</div>`
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main"></div>

As icon return in JSON as protocol-relative URL (without the scheme) //url.
Locally it will use the file:// protocol and that assumes the resource you’re referring to is on the local machine, But it's not.
To avoid this issue locally add http: or https:to image src like <img src=http:${condition.icon}>.
const key = 'b7e1e81e6228412cbfe203819180104';
const url = `https://api.apixu.com/v1/current.json?key=${key}&q=auto:ip`
const main = document.getElementById('main');
$.getJSON(url, function(json) {
const loc = json.location;
const cur = json.current;
const condition = {
text: cur.condition.text,
icon: cur.condition.icon
}
main.innerHTML = `<img src =http:${condition.icon}><div>${condition.text}</div>`
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main"></div>

Related

windows URLSearchParams when changed

My English is not good sorry,
I do not want to let one of the URLSearchParams change.
And when the URLSearchParams is changed, returne to the my input value.
URL address : example.com/action.php?id=1&name=john&penalty=365
<input name='penalty' value='365' hidden>
<script>
$(document).ready(function() {
const url = window.location.href;
const paramspenalt = new URLSearchParams(url.split('?')[1]);
var penaltyvar = $('input[name=penalty]').val();
paramspenalt.set('penalty', penaltyvar);
const resultpenalty = paramspenalt.toString();
window.location = 'action.php?'+resultpenalty+'';
});
</script>
Everything is fine with this code, But the page is constantly loading.
It is very good if the page is loaded only once.
#ksav helping me and
fixed my problem from How do I modify the URL without reloading the page?
:
<input name='penalty' value='365' hidden>
<script>
$(document).ready(function() {
const url = window.location.href;
const paramspenalt = new URLSearchParams(url.split('?')[1]);
var penaltyvar = $('input[name=penalty]').val();
paramspenalt.set('penalty', penaltyvar);
const resultpenalty = paramspenalt.toString();
//****
window.history.pushState("object or string", "Title", 'action.php?'+resultpenalty+'');
//****
});
</script>

How can I delete a favicon on a non self hosted site using Javascript?

<link rel="shortcut icon" href="https://files.writeas.org/favicon.ico" />
Is the code in the site, I can't change this, I can only change the CSS or inject my own Javascript, thus how would I grab this part of the HTML code using Javascript and comment it out / override it thus deleting it?
if you can't delete it you might change it with the following code
(note: a delete might not be enough as many bowsers default to /favicon.ico)
//const ico_url = document.location.origin + '/favicon.ico'
const ico_url = 'https://api.adorable.io/avatar/256/your_icon.png'
let head = document.getElementsByTagName('head')[0]
console.dir(head)
var link;
let links = head.getElementsByTagName('link')
for(let i=0; i<links.length; i++) {
if (links[i].rel == 'icon' || links[i].rel == 'shortcut icon') {
link = links[i]
console.log('old-icon: '+link.href)
link.href = ico_url
console.log('new-icon: '+link.href)
}
}
if (typeof(link) == 'undefined') {
console.log('creating favicon link !')
link = document.createElement('link')
link.setAttribute('rel','icon')
link.setAttribute('type','image/png')
link.setAttribute('href',ico_url) // new favicon ...
document.getElementsByTagName('head')[0].appendChild(link)
}
console.log(link.href)
maybe you can try to replace the head tag ...
let ico_url = 'https://api.adorable.io/avatar/256/head_icon.png'
var head = document.createElement("head");
link = document.createElement('link')
link.setAttribute('rel','icon')
link.setAttribute('type','image/png')
link.setAttribute('href',ico_url) // new favicon ...
head.appendChild(link)
const html = document.getElementsByTagName('html')[0]
html.appendChild(head)
html.replaceChild(head,document.getElementsByTagName('head')[0])
console.dir(head)

Dynamically generated href won't show properly

So I'm trying to make this link appear on my page, but it won't return the /register path, it'll just go immediately the UTMs.... On the site it'll show the href as
domain.com/?utm_campaign...
instead of
domain.com/register?utm_campaign...
Why is that and how can that be fixed?
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
// get the required parameter
const campaign = urlParams.get('utm_campaign');
const source = urlParams.get('utm_source');
const medium = urlParams.get('utm_medium');
var registerationURL = new URL('../register?utm_campaign=&utm_source=&utm_medium=');
registerationURL.searchParams.set('utm_campaign', campaign);
registerationURL.searchParams.set('utm_source', source);
registerationURL.searchParams.set('utm_medium', medium);
var a = document.getElementbyID('test').innerHTML;
a.href = registerationURL;
</script>
<a id="test" href="#">Click here</a>
document.getElementbyID('test').innerHTML returns the string "Click here". Remove the .innerHTML and it should work.
However, this can be done much simpler with the following
var registrationUrl = location.origin + '/register' + location.search;

Join identical variables with different arrays from multiple external js files in JavaScript

I have made an offline web application:
<!DOCTYPE html>
<html dir="rtl">
<head>
<meta charset="utf-8">
<style><!-- some style here --></style>
<script>
var rqid = location.hash.replace('#','');
var js = Math.ceil(rqid / 100);
var id = rqid - ((js - 1) * 100) - 1;
var tg = document.createElement('script')
tg.src = js + '.js'
tg.type = 'text/javascript'
document.head.appendChild(tg);
window.onload = function load() {
var body='<h1>' + title[id] + '</h1> <article>' + content[id] + '</article>';
document.getElementById("body").innerHTML = body;}
</script>
</head>
<body id='body'>
</body>
</html>
The above is the simplified article.html file, which shows articles stored inside external .js files, each with two variables.
1.js contains
title = ['title of article1','title of article2',...,'title of article100'];
content = ['content of article1','content of article2',...,'content of article100'];
2.js contains
title = ['title of article101','title of article102',...,'title of article200'];
content = ['content of article101','content of article102',...,'content of article200'];
For example, article.html#1 loads 1.js into the html, and then shows article1, and article.html#101 loads 2.js and shows article101.
It works fine, but there's a problem with the search engine I have written for this application. The search engine code is quite bulky. Sharing it here will not be possible.
The problem is the identical variables in the .js files, which are overridden one after one.
<script src="1.js"></script>
<script src="2.js"></script>
<script src="3.js"></script>
So, search is done only in 3.js.
The question is: Is it possible to dynamically join title/content arrays in those .js files and have a unified title/content variable like the following, so the search can be performed in all articles?
title = ['title of article1',...,'title of article200'];
content = ['content of article1',...,'content of article200'];
If it is not possible, simply say no but please do not recommend to restructure the stored data.
I would add that the speed/performance is not a problem, in case it is going to be slow.
Here is a simple example of how you could do this without having to restructure your 1.js, 2.js..
For the purpose of this example I've created a pretend fetch, that can get 1.js, & 2.js, if you have any real URL's to test, we should be able to replace the fetch mock with a real one.
const pretenddata = {
"1.js":
`title = ['title of article1','title of article2','title of article100'];
content = ['content of article1','content of article2','content of article100']`,
"2.js": `title = ['title of article101','title of article102','title of article200'];
content = ['content of article101','content of article102','content of article200'];`
};
//lets create a pretend fetch..
function fetch(url) {
function astext() {
return new Promise((resolve) => {
resolve(pretenddata[url]);
});
}
return new Promise((resolve) => {
resolve({text: astext});
});
}
async function test() {
var combined_title = [];
var combined_content = [];
async function getData(url) {
const r = await(await fetch(url)).text();
var d = new Function(`${r}; return [title, content]`)();
combined_title = combined_title.concat(d[0]);
combined_content = combined_content.concat(d[1]);
}
await Promise.all([
getData("1.js"),
getData("2.js")
]);
console.log(combined_title);
console.log(combined_content);
}
test();
When working with globals across multiple files, it is always a good idea to use some kind of globals structure, that way it is much more explicit as to the fact that the data is, in fact, global, and it makes it much less likely to cause issues with scope pollution.
In your case, you can create a basic object called "globals", which will have a title and content property, just like you were with your global variables. In fact, those actually go on the window object by default, so it works exactly the same - just instead of saying window.title, you can say globals.title, etc. The only difference being that the variables will never be accessed accidentally by default scoping.
window.globals = {};
// file1
(function () {
var title = ['title of article1','title of article2','title of article100'];
var content = ['content of article1','content of article2','content of article100'];
globals.title = globals.title ? globals.title.concat(title) : title;
globals.content = globals.content ? globals.content.concat(content) : content;
})();
// file2
(function () {
var title = ['title of article101','title of article102','title of article200'];
var content = ['content of article101','content of article102','content of article200'];
globals.title = globals.title ? globals.title.concat(title) : title;
globals.content = globals.content ? globals.content.concat(content) : content;
})();
// file3
(function () {
var title = ['title of article201','title of article202','title of article300'];
var content = ['content of article201','content of article202','content of article300'];
globals.title = globals.title ? globals.title.concat(title) : title;
globals.content = globals.content ? globals.content.concat(content) : content;
})();
// final results
console.log(globals.title);
console.log(globals.content);

how to delete the <script> in the news I crawlered

Here is my code, when I execute it, there are some information which is from code of original website. They are included in the results.
enter code here
import urllib.request
from bs4 import BeautifulSoup
import re
URLdict=dict()
pageNum=1
while pageNum<2:
user_agent = 'Chrome/58.0(compatible;MSIE 5.5; Windows 10)'
headers = {'User-Agent': user_agent}
if pageNum==0:
response=urllib.request.urlopen('http://www.1905.com/list-p-catid-
221.html')
else:
url = 'http://www.1905.com/list-p-catid-221.html' + '?
refresh=1321407488&page=' + str(pageNum)
request = urllib.request.Request(url,headers=headers)
response = urllib.request.urlopen(request)
first = response.read().decode('utf-8')
BSobj = BeautifulSoup(first, "html.parser")
for a in BSobj.findAll("a", href=True):
if re.findall('/news/', a['href']):
URLdict[a['href']] = a.get_text()
#print(URLdict)
for link, title in URLdict.items():
print(title, ":", link)
ContentRequest = urllib.request.Request(link,headers=headers)
ContentResponse = urllib.request.urlopen(ContentRequest)
ContentHTMLText = ContentResponse.read().decode('utf-8')
ContentBSobj = BeautifulSoup(ContentHTMLText, "html.parser")
Content = ContentBSobj.find("div", {"class": "mod-content"})
if Content is not None:
print(Content.get_text())
pageNum=pageNum+1
I checked the original code,these information are from ,they are like these:
enter code here
var ATLASCONFIG = {
id:"1197971",
prevurl:"http:www.1905.com/news/20170704/1197970.shtml#p1",
nexturl:"http:www.1905.com/news/20170704/1197970.shtml#p1",
shareIframe:"http://www.1905.com/api/share2.php?....
}
These information appeared in the results rather than my code. I can not send more than two links, so I deleted "//",I want to ask how to delete these,
Use delete to remove a property from an object.
var ATLASCONFIG = {
id:"1197971",
prevurl:"http:www.1905.com/news/20170704/1197970.shtml#p1",
nexturl:"http:www.1905.com/news/20170704/1197970.shtml#p1",
shareIframe:"http://www.1905.com/api/share2.php?...."
}
delete ATLASCONFIG["shareIframe"];
console.log(ATLASCONFIG);

Categories