简体   繁体   中英

Display requested JSON feed as URL

I have a form that makes a request for a JSON feed, and displays the results. I need to be able to provide a link to the raw feed to the user as well. I have the following code that pulls the selections from inputs and generates a URL for the request:

document.getElementById('region').addEventListener('submit', function (event) {
  event.preventDefault();

      window.location.href = '/editorialPortal' + '?' + this.id + '=' + this.options[this.selectedIndex].value;

});

I need to be able to put window.location.href = '/editorialPortal' + '?' + this.id + '=' + this.options[this.selectedIndex].value; window.location.href = '/editorialPortal' + '?' + this.id + '=' + this.options[this.selectedIndex].value; into an anchor link, but having trouble getting that setup.

I have this <a href="<' + "script type='text/javascript'>window.location.href = '/editorialPortal' + '?' + this.id + '=' + this.options[this.selectedIndex].value;"'</script>">JSON</a> <a href="<' + "script type='text/javascript'>window.location.href = '/editorialPortal' + '?' + this.id + '=' + this.options[this.selectedIndex].value;"'</script>">JSON</a> , but its not working correctly due to quotation mark placement.

You'll see in the console.log event that the URL is generated by the form in this fiddle I need to be able to set that generated URL as the JSON feed it returns

Let's assume that the <a> you want to update already exists, already has the text of 'JSON', and has an id of link (if not, badrequest's answer shows you how to add a new <a> to the page). So we just need to update it's href attribute with the selected values.

var regionBox = document.getElementById('region'),
    region = regionBox.options[regionBox.selectedIndex].value,
    durationBox = document.getElementById('duration'),
    duration = durationBox.options[durationBox.selectedIndex].value,
    link = document.getElementById('link'),
    newHref = '/editoralPortal/?region=' + region + '&duration=' + duration;

link.href = newHref;

You need to create the anchor tag dynamically on the DOM

// create anchor and set attributes

var anchor = document.createElement('a');
anchor.setAttribute('href', 'your generated link goes here');
anchor.innerHTML = 'Whatever you want to show up on page';

// nest anchor tag somewhere on page

var blabla = document.getElementById('blabla);
blabla.appendChild(anchor);

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM