【问题标题】:cannot return after successful json request [duplicate]json请求成功后无法返回[重复]
【发布时间】:2017-11-21 05:55:46
【问题描述】:

我已经从这种类型的函数进行了 json 调用,我得到了结果,但是我无法将此值返回给另一个函数

get_target_amount(满)

这是我的职责。在console.log(get_target_amount(full)) 之后结果未定义。这是什么原因?

 function get_target_amount(full) {
            var target = '';
            var param = {};
            param.sub_category_id = full["sub_category_id"];
            param.project_month = full["project_month"];
            jQuery.post(site_url + '/Progress_project_create/get_target_amount', param, function (response) {

                        if (response !== null) {
                    target = response.target_amount;

                } else {
                    target = 'Target amount not found';
                }
                return target;
            }, 'json');
        }

【问题讨论】:

  • @Phil 给一个解决方案的伙伴。我用这个传递了一些价值
  • 您是否费心阅读其他帖子的答案?

标签: json ajax return


【解决方案1】:

这里的问题是 Ajax 调用的异步特性。

请将基于 target 变量的代码移动到 get() 函数中的回调函数中。

function(response){//Write all your code here.}

目前,get_target_amount() 无需等待 ajax 调用完成即可返回。因此,您会得到空值。

您可以考虑另一种选择,例如让您的 ajax 调用同步。 然后浏览器暂停/冻结页面,直到 ajax 函数完成。这是不可取的,因为它会使用户不必要地等待页面响应。

此外,您在回调函数中的 return 语句不会在任何地方引用

【讨论】:

  • 比x工作得很好
  • 不客气
猜你喜欢
  • 1970-01-01
  • 2018-11-05
  • 2018-02-11
  • 2021-04-09
  • 2018-09-12
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2012-12-04
相关资源
最近更新 更多