0

When i attempt to retrieve a JSON with ajax i first had problems with CORS which i fixed by enabling crossDomain to true and adding dataType as jsonp (notice the 'p'). When running the script it returns a null instead of the data it was supposed to get from the JSON

<html>
<head>


</head>
<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>

var json = (function() {
        var json = [];
        $.ajax({
            'async': false,
            'global': false,
            'crossDomain': true,
            'method': "get",
            'url': "products.json",
            'dataType': "jsonp",
            'success': function (data) {
                json = data;
            }
        });
        return json;
    })();
console.log(json);



</script>
</body>
</html>

The JSON

{
    "items": [{
        "title": "Express"
    }, {
        "title": "Unexpress"
    }]
}

I expect a json but it returns null and a message in console: "Uncaught SyntaxError: Unexpected token :" at line 2 of the JSON.

16
  • Where are you getting JSON from ? Commented Aug 19, 2019 at 19:53
  • The hard drive. It will get the json from c:\products.json Commented Aug 19, 2019 at 19:54
  • forget the last comment, i get it from the project root Commented Aug 19, 2019 at 19:55
  • Well, try to open Inspector (ctrl + shift + i) and go to network tab, and refresh page and look what you get there, there should be a request for it Commented Aug 19, 2019 at 19:56
  • Yes, i do get it with status "finished" Commented Aug 19, 2019 at 20:04

2 Answers 2

0

You havent defined jsonpcallback, refer to below link this may help

ajax 'GET' call returns jsonp okay but callback produces 'undefined' data

Sign up to request clarification or add additional context in comments.

Comments

0

Change 'dataType': "jsonp", to 'dataType': "json",

4 Comments

that will prompt me a Access to XMLHttpRequest at 'file:///{MY_PATH}/products.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
@userct if you would have stated that in your question, we could have solved this problem for you a long time ago. What you are doing is impossible. Literally impossible, as in there is no way that you will ever use ajax to get json from your filesystem using a standard web browser.
The best you can do is convert the .json file into a .js file that calls a method, and include it like any other or use the jsoncallback param to tell jquery the name of the method within the .js file.
Do you need to config cors in your back-end to work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.