JQuery的 - 如何使用Ajax调用的返回值是Ajax调用之外如何使用、返回值、JQuery、Ajax

由网友(゛__那些画面〞)分享简介:我有一个Ajax调用。我把返回值(数据)在一个变量称为MYDATA。我想用这个变量Ajax调用之外。做笔记,我不能将我的code在Ajax调用成功的一部分。我不会详细的原因,因为它会增加混乱。所以,问题很简单。有没有一种方法来使用Ajax调用之外Ajax调用的返回值?预先感谢您的答复。干杯。马克·$。阿贾克斯({键入:...

我有一个Ajax调用。我把返回值(数据)在一个变量称为MYDATA。我想用这个变量Ajax调用之外。做笔记,我不能将我的code在Ajax调用成功的一部分。我不会详细的原因,因为它会增加混乱。所以,问题很简单。有没有一种方法来使用Ajax调用之外Ajax调用的返回值?预先感谢您的答复。干杯。马克·

  $。阿贾克斯({
    键入:POST,
    网址:为file.php,
    数据:ajaxData,
    成功:功能(数据){
        VAR MYDATA =数据;
    }
});

警报(MYDATA); //  - >这是行不通的
 

解决方案

简短的回答:不,你不能,作为一个在AJAX的全称是异步,因此该脚本不等待的AJAX调用完成了。

可以,如果你愿意,使用间隔轮询看MYDATA是否设置:

  VAR MYDATA = NULL;

$阿贾克斯({
    键入:POST,
    网址:为file.php,
    数据:ajaxData,
    成功:功能(数据){
        VAR MYDATA =数据;
    }
});

VAR timerId =的setInterval(函数(){
   如果(MYDATA!== NULL){
      //你的code
      clearInterval(timerId);
   }
},1500); //改变这种以自己的喜好,其实并不重要
 
剪下边缘 jQuery 与预测提取和 ASP.NET AJAX 程式库

但这个假定为file.php 将永远不会在数据返回null

I have an ajax call. I put the return value (data) in a variable called mydata. I would like to use that variable outside the ajax call. Do note that I can not incorporate my code in the success part of the ajax call. I will not detail the reasons as it will add confusion. So the question is simple. Is there a way to use the return value of an ajax call outside that ajax call? Thank you in advance for your replies. Cheers. Marc

$.ajax({
    type: "POST",
    url: "file.php",
    data: ajaxData,
    success: function(data) {
        var mydata = data;    
    }
});

alert(mydata); // -> This is not working

解决方案

Short answer: No you can't, as A in AJAX stands for "Asynchronous", so the script doesn't "wait" for the AJAX call to complete.

You can, if you want, use an interval polling to see whether mydata is set:

var mydata = null;

$.ajax({
    type: "POST",
    url: "file.php",
    data: ajaxData,
    success: function(data) {
        var mydata = data;    
    }
});

var timerId = setInterval(function() {
   if(mydata !== null) {
      // your code
      clearInterval(timerId);
   }
}, 1500); // change this to your liking, doesn't really matter

But this assumes that file.php will never returns null in data

阅读全文

相关推荐

最新文章