使用jquery ajax处理从php获取的数组的问题 [英] Problems with handling arrays gotten from php by using jquery ajax

查看:115
本文介绍了使用jquery ajax处理从php获取的数组的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,早上好.

在尝试使用从php获取的数组时,我仍然遇到一些问题.问题是,当我得到一个数组时,不能在成功函数"之外使用它.所以这就是正在发生的事情.

I still have some problems trying to use arrays which were gotten from php. The problem is that when I got an array , I can not use it out of the "success function". So this is what is happening.

我创建了一个名为"langs"的变量来保存数组的信息:

I create a var called "langs" to save array's information:

var langs=[];

然后,当我使用console.log获取成功的打印阵列信息INSIDE函数时,我的代码如下:

Then, when I use console.log for print array's information INSIDE function success, my code seems like this:

$.ajax({
      type: 'POST',
      url: '/ws/languagesForJs',
      dataType: 'json',
      success: function(result) {
            langs=result;
            console.log(result)         
      },
  });

效果很好!!我可以看到阵列的信息.看起来像这样:

It works Great!! I can see the array's information. It looks like this:

Object {es: Object, en: Object}
 en: Object
       lang_ext_name: "en_US"
       lang_id: 2
       lang_iso: "en"
       lang_name: "Inglés"
       lang_url: "en"
      __proto__: Object
 es: Object
       lang_ext_name: "es_PE"
       lang_id: 1
       lang_iso: "es"
       lang_name: "Español"
       lang_url: "es"
 __proto__: Object
 __proto__: Object

但是,当我使用console.log获取打印阵列信息时,功能成功:

HOWEVER,When I use console.log for print array's information OUTSIDE function success:

$.ajax({
      type: 'POST',
      url: '/ws/languagesForJs',
      dataType: 'json',
      success: function(result) {
            langs=result;

      },
  });
            console.log(result)

它只返回;

[]

真心的,我不知道为什么会这样.也许我缺少某种功能的理论或某些东西.我一直在网上寻找信息;但是,似乎没有人需要一个在成功功能之外的数组.我尚未找到任何相关信息.

Sincerely, I do not know why is it happens. Maybe I'm missing some function's theory or something. I've looked for info on the web;however, it seems that no one needs an array outside success functions. I haven't found any information about it.

我希望有人能帮助我.谢谢

I hope someone can help me. Thanks

顺便说一句:对不起,我的英语不好.这不是我的母语.

Btw: Sorry for my bad english. It is not my mother language.

推荐答案

这里有2个问题.

  1. 结果是成功回调的本地结果.您可以在回调之外访问lang,因为它似乎没有全局作用域.
  2. 回调是异步发生的.这可能会导致console.log调用在成功回调之前发生.研究jQuery ajax承诺对象 http://api.jquery.com/jQuery可能是值得的.ajax/.

这篇关于使用jquery ajax处理从php获取的数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆