1

我正在使用 html5 制作网页。问题是我从一个 url 中获取一个 json 并在控制台上打印它的结果。我在函数中得到了预期的结果,但没有在函数之外得到它。即使变量是全局的。请看下面的代码

<script src="jquery-1.8.3.min.js"></script>

<script>
$(document).ready(function(){
    var result;
    $.ajax({
        type: 'GET',
        url: 'http://192.168.1.5:3333/abc.json',
        async: false,
        jsonpCallback: 'jsonCallback',
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(data) {
            //var result = $(this).html(JSON.stringify(data));
            //console.log(JSON.stringify(data));
            result = JSON.parse(JSON.stringify(data));
            console.log(result); // Result : 1
        },
        error: function(e) {
            alert(e.message);
        }
    });

   console.log("here::"+result); // Result : 2
});
</script>

我得到的结果是

    2  here:undefined
    1    object                     (json)

我需要这个 json 来解析。

4

1 回答 1

3

文档对此非常清楚:

跨域请求和 dataType: "jsonp" 请求不支持同步操作。

基本上,这意味着您async: false根本没有被使用,这解释了这种行为。

也可以看看:jQuery.ajax()

于 2012-12-28T13:35:50.000 回答