Executing Javascript code that has been retrieved using the XMLHttpRequest method in a

Would it be feasible to modify this code to function recursively if the redirects to the js file that needs to be executed?

function loadScript(scriptUrl)
{
        var xhr = new XMLHttpRequest();
        xhr.open("GET", scriptUrl);
        xhr.onreadystatechange = function()
        {
            if ((xhr.status == 200) && (xhr.readyState == 4))
            {
                eval(xhr.responseText);
            }
        };
        xhr.send();
}
loadScript("http://www.myurl.com");

Answer №1

Why not consider this alternative:

$("head").append("<script src='http://myurl.com' type='text/javascript'></script>"); 

While it is possible to achieve the same result without using jQuery, the essence remains the same. If you are simply fetching data from a URL that only requires GET arguments (or none at all), it is more convenient (and secure) to append a new script element with its source included.

By doing so, it also addresses any redirection concerns as the browser will automatically follow the redirect.

Answer №2

When a URL sends you to a different location, it will typically return a 301 status code instead of a 200 status code. In this scenario, your check should be:

if ((xmlhttp.status == 200 || xmlhttp.status == 301) && xmlhttp.readyState == 4)

Alternatively, you can choose to allow all statuses except for the ones indicating errors:

if (xmlhttp.status < 400 && xmlhttp.readyState == 4)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to include a JavaScript variable within CSS styling?

I am currently implementing a dropdown menu system where the image of a parent div changes on mouse hover over a link, and reverts back when the mouse moves away. I have this functionality set up using a variable in my HTML code. Is there a way for me to m ...

send the value from the input field to the designated button - link the two buttons

My goal is to create a feature where users can click on a button within the map and open an external page in Google Maps with specific dimensions (500 X 600) and without the Menu bar, Tool bar, or Status bar. // Custom Button Functionality by salahineo ...

Click on an Object within a modal window using JavaScript in Internet Explorer 8

I'm facing a strange issue with the SELECT object in a Modal Window. Within my HTML code, I have a button that opens a modal window when clicked. Inside this modal window, a JSP page is loaded. On this JSP page, there is a dropdown list created using ...

Detecting modifications to an array with MobX

Today marks my first foray into learning MobX and I am eager to discover how to track all array changes (insertions, deletions, etc) with MobX. A practical example would definitely help clarify this: const TodoList = ({todos}) => ( <ul> ...

Issues with the Jquery feedback plugin's functionality are currently preventing it

I wanted to incorporate a feedback feature into my web application. To do this, I searched on Google and found a suitable jQuery plugin. I followed the documentation provided by the plugin, including the library in my HTML file, and then wrote the code as ...

Transitioning create-react-app from JavaScript to Typescript

A few months ago, I began a React project using create-react-app and now I am interested in transitioning the project from JavaScript to TypeScript. I discovered that there is an option to create a React app with TypeScript by using the flag: --scripts-v ...

Steps to create two jQuery dropdown filters for multiple identifiers:

Is it possible to create two dropdown menus that can be used to filter a gallery of images? I am currently facing an issue where the filtering functionality is not working after adding a name attribute to the image IDs. When I select an option from the s ...

What is the reason behind the inability of this YouTube instant search script to enable fullscreen mode?

Looking to implement a Youtube instant search on my website, I came across this script that seems ideal for my needs. However, I'm facing an issue where the iframe is not displaying the allowfullscreen property. Can anyone assist with this problem? Th ...

What is the significance of the "@" in JXON conversion in JavaScript?

Looking at an XML structure like the one below: <calendar> <month year="2013" num="5"> <day num="1"> </month> </calendar> I decided to convert it to JSON using MDN's JXON Snippet 3. https://developer.moz ...

Shining a component (or persona) however essentially duplicate a distinct term

Is it possible to highlight an element or word, but still copy a different word when hitting ctrl+c? For example, imagine I have an emoji represented by: Original text: :heart: Output in HTML: <span background={...logic here}></span> I am ...

Is there a way to bypass the default layout on app router in Next.js and implement our own custom page layout

Utilizing a default layout in layout.jsx, I passed all my other pages as children through props. In the page router, we typically configure the router path to specify which layout to use. However, in this new system, I am facing challenges with coding it. ...

Color key in square shape for graph legend

I am looking for legend colors in square shape, but I don't want them to appear as square boxes on the graph. https://i.stack.imgur.com/Of0AM.png The squares are also showing up on the graph, which is not what I want. https://i.stack.imgur.com/Az9G ...

What are some secure methods for integrating iframes into an Angular 7 project?

Is there a secure method to set the URL for an iframe without bypassing security measures like using this.domsanitizer.bypassSecurityTrustResourceUrl(url)? While this approach may be flagged as a high vulnerability by tools such as Veracode, is there a w ...

Creating registration and login forms using an express server

Currently, I'm in the process of creating a basic website on my localhost that incorporates a signup form along with other essential HTML elements. The setup for the signup procedure went smoothly as planned. When a user completes the form and submits ...

Retrieving a list from an ASP.NET MVC controller using ajax

After searching for a solution to my problem on search engines and Stack Overflow, I came across various answers but none of them seemed to work for me. Here is the code snippet from my controller: [HttpGet] public JsonResult Get() { var c ...

Problem with CKEditor's Autogrow functionality

I am experiencing a problem with CKEditor's autogrow functionality on my webpage that is built using MVC and includes ajax posts that return partial views. Whenever I trigger certain $ajax requests (specifically those returning partials without reload ...

Issue with decodeURI function causing hyperlinks to display as plain text

I have been developing a Sharepoint App that includes a feature to extract contact details from a list on the Sharepoint site. Below is a snippet of my code: var currentOpeningContent = '<h4 onclick="ShowJobDetail(\'' + encodeURI(cu ...

Form_Open will automatically submit - Ajax Submission in CodeIgniter

I am facing an issue with submitting my form via Ajax. Despite setting up a function to prevent the page from refreshing upon submission, it seems like the form still refreshes the page every time I click submit. I even tried creating a test function to lo ...

Can the line "as is" be included in HTML code?

Can I incorporate the following JavaScript and JSON expressions directly into HTML code? CONTRATE > 50 && SALINC <= 50 || RETAGE >= 50 { "CONTRATE": 0, "SALINC": 0, "MARSTATUS": "single", "SPOUSEDOB": "1970-01-01" } I want to be able to ...

Copy the style of a chosen element and apply it to another element

One of the challenges I'm facing involves a dynamic span element that changes based on color selection: <span class="color checked" style="background-color: #ff0000">Red</span> In addition, I have an image element wit ...