Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 第一次尝试时未定义$post调用返回数据_Jquery_Ajax - Fatal编程技术网

Jquery 第一次尝试时未定义$post调用返回数据

Jquery 第一次尝试时未定义$post调用返回数据,jquery,ajax,Jquery,Ajax,我需要将jquery$.post调用返回的数据存储在名为result的变量中。 除了第一次单击结果返回为未定义外,下面的代码可以正常工作。。。 第二次单击时,它将按预期从php文件返回数据。 谢谢 您应该使用result作为全局变量 全局变量将允许您在范围外使用变量: var result; $(function(){ $('a').on('click',function(){ var cv = $(this).data('cv'); var url= '/e

我需要将jquery$.post调用返回的数据存储在名为
result
的变量中。 除了第一次单击
结果
返回为未定义外,下面的代码可以正常工作。。。 第二次单击时,它将按预期从php文件返回数据。 谢谢


您应该使用result作为全局变量

全局变量将允许您在范围外使用变量:

var result;
$(function(){
    $('a').on('click',function(){
      var cv = $(this).data('cv');
        var url= '/echo/json/';
      $.post(url,{contentVar:cv},function(data)
      {
        result = data;
        //you don't need any return, its callback function 
      }).done(function(){
          alert(result);
      });

    });
});
您可以找到以下方面的更多信息:

像这样试试看

var result=null;// initially initialize this variable
$('a').on('click',function(e){
   e.preventDefault();// use this line to prevent its default behaviour
   var cv = $(this).data('cv');
   var url= '_php/myphp.php';
   $.post(url,{contentVar:cv},function(data)
   {
      result = data;
      alert(result);// first alert
      return result;    
   });
   alert(result);// its global now, check this too
});
如果未修复,则使用
async:false
选项。同步调用
Ajax代码
,以便初始化
result变量
,并在
Ajax调用
后获得
结果。使用
.done()
方法,等待Ajax调用获得成功响应,然后发出结果警报

$('a').on('click',function(){
  var cv = $(this).data('cv');
  var url= '_php/myphp.php';
  $.post(url,{contentVar:cv},function(data) {
    result = data;
    return result;    
  }).done(function() {
      alert(result);
  });
});

您可以在
结果
的回调中替换单词
数据
,而不是在事实发生后分配它。可能的重复不能从这样的异步调用返回数据。。。可能有1000个问题与相同的主题。。。解决方案是使用回调函数来处理ajax返回的值,如前所述,这些问题中的每一个问题都与它是否异步无关。当您调用变量时,异步唯一会影响其性能的事情。如果你在集合后调用它,你会得到正确的值。我想你错过了一些东西。会的。你应该在返回前将警报放在post回调中
$('a').on('click',function(){
  var cv = $(this).data('cv');
  var url= '_php/myphp.php';
  $.post(url,{contentVar:cv},function(data) {
    result = data;
    return result;    
  }).done(function() {
      alert(result);
  });
});