$ .get并获得价值 [英] $.get and get value

查看:115
本文介绍了$ .get并获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 function get(){
      $.get('/get.php', function(data) {
          alert('one: ' + data)
          return data;
      });
  }

  var test = get();
  alert('two:' + test);

在get.php中:

<?php echo "number"; ?>

为什么一个提醒显示
一:数字

但两个提示显示
两个:未定义

我怎么能在函数外得到这个值?

How can i get this value outside function?

推荐答案

$。get 调用是异步。这意味着你传递了一个回调(你的函数(数据){...} ,它将通过调用的结果执行。你不能从回调内部返回 - 当它被执行时,你的外部函数(执行 $。get )已经返回。尝试这样的事情:

The $.get call is asynchronous. That means that you pass it a callback (your function(data) { ... }, which gets executed with the result from the call. You can't return from inside that callback - when it is executed, your outer function (doing the $.get) has already returned. Instead, try something like this:

// callback will be executed with the response from your GET request
function get(callback){
    $.get('/get.php', callback);
}

// Call get with a callback receiving the response
get(function(data) {
    alert('two:' + data);
});

这是在编写javascript代码时必须习惯的模式。

This is a pattern you will have to get used to when writing javascript code.

这篇关于$ .get并获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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