简体   繁体   English

ajax回调JSON对象返回未定义

[英]ajax call back JSON object returns undefined

I have looked at many many posts about this subject and have tried several of the solutions but i can not seem to get it right. 我看过很多关于该主题的文章,并尝试了几种解决方案,但我似乎做得不好。

last attempt 最后一次尝试

function checkzip(x){  

       $.ajax({
       type:'POST',
       url:'zipcheck.php',
       data:{zip: x},
       async: false
    }).done(function(r){
        rates(r);
    });
}

function rates(r){
    alert (r);
    if (r !== 'none'){
    m = JSON.parse(r);
    return m;
    }
    else {
        return false;
    }
}

json being returned is {"rateA":"125","rateB":"80","rateC":"150","rateD":"130"} 返回的json是{“ rateA”:“ 125”,“ rateB”:“ 80”,“ rateC”:“ 150”,“ rateD”:“ 130”}

so i want to be able to: 所以我希望能够:

new_rate = checkzip('77090');

and

alert (new_rate.rateA);

but I am getting undefined for the returned value 但是我对于返回值不确定

I have tried passing the function in the success: AND .done(), i have tried returning it directly from both instead of passing to a separate function as well while setting async: false. 我尝试成功传递函数:AND .done(),我尝试直接从两者返回它,而不是在设置async:false时传递给单独的函数。 I have tried placing the ajax call withing a function inside the zipcheck() function and then calling it from within there as well. 我试过将ajax调用和一个函数一起放在zipcheck()函数中,然后从那里调用它。 I am missing something along the lines of creating an object from ajax or working with asynchronous functions. 我缺少从ajax创建对象或使用异步函数的思路。

You're correct in thinking your problem is with asynchronicity. 您认为问题与异步有关是正确的。 You basically need to do any handling of the response inside the rates() function, rather than having checkzip() return a value. 基本上,您需要在rates()函数中对响应进行任何处理,而不是让checkzip()返回值。 If you put your alert() call inside the rates() method, you should see some output. 如果将alert()调用放入rates()方法内,则应看到一些输出。

function checkzip(x) {  
       $.ajax({
       type:'POST',
       url:'zipcheck.php',
       data:{zip: x},
       async: false
    }).done(function (r) {
        rates(r);
    });
}

function rates(r) {
    alert(r);
    if (r !== 'none') {
        var m = JSON.parse(r);
        // Do something with m now.
        alert(m.rateA);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM