JavaScript unable to access JSON document

Similar Inquiry:
Accessing JSON service from localhost or file://

<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$.getJSON('http://game4u.comuf.com/songs.json', function(data) { 
  var output = data.music[0].url; 
  document.getElementById("placeholder").innerHTML = output;

});
</script>

I am facing an issue where the JSON file (music[0].url) does not display in the browser when I execute this code. The HTML code is being run locally, not on the same server as the website.

Answer №1

When testing my HTML code, I run it locally rather than on the same server as the website.

This could be the issue. The getJSON function is an "ajax" call, and those are restricted by the Same Origin Policy. Your local file system does not have the same origin as

http://game4u.comuf.com/songs.json
(although some browsers may consider the local file system to match any origin; most do not).

If you have control over the content at

http://game4u.comuf.com/songs.json
, you can consider using JSON-P instead of JSON. JSON-P bypasses the restrictions of the Same Origin Policy. Another option is Cross-Origin Resource Sharing, which requires action on the server end to grant access to the origin "null" and also requires a browser that supports it (most modern ones do, but IE9 may require workarounds such as using XDR instead of XHR object; jQuery doesn't handle this automatically, though there are plug-ins available).


Additionally, as Musa mentioned, your JSON data is invalid. It would become valid if you fix the backslashes in the URL (they should be forward slashes [/] instead of backslashes [\]) and remove the trailing comma at the end of the list, which is not allowed in JSON.

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

obtaining a JsonDoc by reference from a function

Here is a method that returns a jsonDoc as a reference: bool MyClass::jsonTest(rapidjson::Document & rjsonDoc) { rjsonDoc.SetObject(); rapidjson::Value val(rapidjson::kObjectType); val.AddMember("a", 1, rjsonDoc.GetAllocator()); val.A ...

Like the Word outline view, the list view can be easily collapsed and expanded with a simple click

I've seen a few examples, but I haven't been able to achieve what I'm looking for. I need to extract text from a field and convert it into an outline view similar to the one in Word. Is this possible? Any help would be greatly appreciated. I ...

Retrieving the value of a JavaScript variable in PHP

Let me provide some background before we delve into the main issue. I am currently working on a simple game that includes leaderboards and high scores. After a player loses, an input field appears where they can enter their name to submit their high score. ...

Customizing Electron Button Settings

I'm attempting to configure buttons in electron and shell for opening files in a specific location. For example, my file is located at /Users/***/Desktop/CD-Przemek/documents/QuickStartGuideWN-H1.pdf. Although I have already tried the solution provid ...

Errors are thrown when utilizing hydration with RTK Query

Looking for a solution with my local API and RTK Query, I've encountered an issue when implementing server-side rendering (SSR). Here's the code snippet I'm working with: const api = createApi({ reducerPath: 'data', baseQuery: ...

Exploring the functionality of componentWillReceiveProps within functional components

Embarking on my journey with functional components after extensively working with class components. While experimenting, I encountered a challenge: how can I incorporate the functionality of componentWillReceiveProps within the context of the useEffect h ...

Creating interactive images with text overlays using HTML5 and JavaScript Canvas on user click

Hello StackOverflow community! I'm a newcomer to JavaScript programming and currently facing some challenges with the HTML5/JavaScript Canvas Combo. I have a button that, when clicked, is supposed to verify certain lines and then display an image (pr ...

Using jQuery Mobile: Implementing listview data-filter for multiple data sets

I'm working on a JQM page with two data-role="listview" elements. Both of them are using the same data set, but one listview displays only text while the other includes icons as well. My goal is to implement the data-filter="true" option for both lis ...

Show validation message using Bootstrap near the submit button

My form consists of around 40 questions, some required and some optional. Upon clicking "submit," I utilize Bootstrap's form-validation.js to verify the form before submission, which works seamlessly. However, due to the length of the form, when a us ...

Is it possible to detect a swipe event without relying on third-party libraries

Is there a way to detect a swipe instead of a click using only pure jQuery, without relying on jQuery Mobile or external libraries? I've been examining the TouchSwipe source code, but it contains a lot of unnecessary code for what I really need - sim ...

Transferring the value of a TextBox to another TextBox in ASP.NET across multiple rows

I have around 10 rows where I need to duplicate the value of one TextBox into another. A specific ID can be assigned to the first TextBox to achieve this, but I am seeking a more general function that can copy TextBox values in each row in ASP.NET. This i ...

Modifying the maximum length of input fields in HTML, Javascript, and PHP is possible by adjusting the value through

Hi there, I'm facing an issue that should be easy for you guys to help me with. I recently discovered a security flaw while using the maxlength function in HTML. Users can easily modify the maxlength attribute by inspecting elements on the website, wh ...

What is the best way to extract only the plain text without the JSON data?

I have a specific format in my database where text is stored as shown below: {"en":"My super title is fantastic"} When I loop through to retrieve the value, I end up with: {"en":"My super title is fantastic"} What I actually want is just the text witho ...

The concept of an undefined object without a question mark is frowned upon

Consider the following code snippet: app-config.json { "auth": { "clientId": "acb610688b49", }, "cache": { "cacheLocation": "localStorage" }, "scopes": { "loginRequest": ["openid", "profile", "user.read"] }, "resources": { " ...

Sort through nested objects

Trying to filter an array of movies by genre using a function but encountering a TypeError: TypeError: movie.genres.some is not a function. (in 'movie.genres.some(function(item){return item.name === genre;})', 'movie.genres.some' is und ...

Ways to effectively handle diverse Angular module dependencies

Although I am still new to Angular, I have been striving to write more modular code and rely less on cramming logic into the controller. Instead, I have been utilizing independent services. However, a recurring issue I am facing is having to re-declare the ...

Troublesome Outcome: Next.js Forms Function Smoothly in Local Environment but Encounter Issues when Deploy

I am facing a puzzling issue with my Next.js application. Despite successfully using Nodemailer locally to submit forms, I keep encountering an "Internal Server Error" when deploying to cPanel. I have tried different solutions, but the problem persists. As ...

Creating a dynamic table in VuetifyJS by populating it with data in real-time

Dealing with a dynamically changing table columns can be tricky. This means that hardcoding the template for the table like this example won't work: <template> <v-data-table :headers="headers" :items="items" hide-actions cl ...

Rejuvenating controllers in AngularJS with stateProvider when page is refreshed

There is a state in my code that links to a different page and a different controller. Here's how it looks: .state('productEdit', { url: '/productEdit/:id', templateUrl: '/App/Main/views/produc ...

Methods for showing Internet Explorer not supported in Angular without needing to import polyfills

Due to the deprecation of IE in Angular 12, I need to inform users to switch to a supported browser by displaying a static warning on my page. To achieve this, I have implemented a simple snippet in the index.html file that appends a CSS class to the body ...