简体   繁体   中英

Get JSON with AJAX in javascript returning NULL instead of JSON object

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.

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

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

将“ dataType”:“ jsonp”更改为“ dataType”:“ json”,

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