Extract data from a text file on another server using jQuery and JSONP

Hi, I'm trying to make something very simple, but since I'm pretty new to JSONP, I'm struggling with it. All I want to do is get JSON from a text file in another domain (so I need to use JSONP to solve cross domain problems). I am using the following code:

$.ajax({ type: "GET", dataType: 'jsonp', url: "http://www.topshop.com/aboutus/show.txt", success: returnedMessage }); function returnedMessage(data) { console.log(data.message); } 

I know that JSONP returns JSON as a function, but I don't know how to print the resulting json objects on the console. I am sure that this can be done, although, as I can see on the NET tab of Firebug, it returns JSON as an answer. In the Firebug console, I get an invalid tag message, which I think is due to the fact that I am not considering the JSONP request correctly. Can anyone help me with this?

+4
source share
2 answers

Your JSONP format is incorrect. The file contains JSON data, not JSONP data. The error message you receive is related to the browser trying to run the object as code. You should put a function call around the JSON data:

 callback({ "message": "This is coming from staging." }); 

Since the text file cannot use the query string with the name of the function that was sent to it, you must specify the name of the function using the jsonpCallback property:

 $.ajax({ type: "GET", dataType: 'jsonp', jsonpCallback: 'callback', url: "http://www.topshop.com/aboutus/show.txt", success: returnedMessage }); 
+2
source

This should work:

 $.getJSON('http://www.topshop.com/aboutus/show.txt?callback=?', function(data) { console.log(data); }); 
0
source

Source: https://habr.com/ru/post/1337310/


All Articles