2

我正在尝试下面的代码通过 AJAX 返回一个数组并尝试提醒返回值,但它显示我未定义,同时使用相同的逻辑获得正确的值。

这是我的 HTML 和 JS 代码:

HTML

<body>
    <div>
    <input type="button" id="getMI" />    
    </div>
</body>

JS 代码(未定义)

var getId = function () {
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        contentType: "application/json",
        success: function (res) {
            objLen = res.length;
            var arrElems = [];
            for (i = 0; i < objLen; i++) {

                arrElems[i] = res[i].ids;

            }
            return arrElems;

        },
        error: function (e) {
            return e;
        }
    })
}

JS 代码(获取正确的值)

var getId = function(){
 var nums = [];
    for(i=0;i<5;i++) 
    {
        nums[i] = i+1;
    }
 return nums;
}

警报值

$('#getMI').click(function(){
    var ids = getId();
    alert(ids)      
})

当我直接警告输出(block_faces)时,它给了我正确的值,但是当我尝试返回它显示未定义时。

谁能帮我知道我哪里出错了?

4

4 回答 4

0

Guys I would like to share something I came to know about solution of my issue. To make call successfully I've used async:false following one of the suggestion but I got some issues later on. Issue like I was not able to get success response on Safar browser. After posting a question here I came to know that using async:false is totally wrong approach.

Here I'm pasting the link of comments and discussion on that.

Getting error in AJAX response on Safari browser only

Hope it'll help you guys. Thanks.

于 2013-02-21T10:55:29.387 回答
0

You can't return from an ajax callback. First of all, it doesn't have anywhere to return to. Second, unless it is synchronous (don't do that), the code that comes after the ajax call is likely to execute first and you can't get the value you need.

You must use the success callback to handle all of your post-ajax operations, or you can bind more callbacks to the jqXHR object that is returned via .done:

var getBlockFaceId = function(){
    return $.ajax({

$("#getBFI").on('click', function () {
    getBlockFaceId().done(function () { alert(ids); });
});
于 2013-02-08T16:00:20.040 回答
0

return 关键字返回触发 return 的当前函数的值。因此,您当前正在编写的返回是返回成功函数的值。因此,为 js 定义一个全局变量并更新该值,如下所示

var block_faces = '';
        $.ajax({
                        type:'GET',
                        url:url,
                        dataType:'json',
                        contentType: "application/json",
                        success:function(res){
                            objLen = res.length;
                            var block_faces = [];                   
                            for(i=0;i<objLen;i++)
                            {

                                block_faces[i] = res[i].block_face_id;

                            }  

                        },
                        error:function(e){
                            block_faces = e;
                        }
                    })
于 2013-02-08T16:03:50.553 回答
-1
于 2013-02-08T15:59:55.643 回答