Javascript 在函数内执行 jquery ajax 调用的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3963906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:53:05  来源:igfitidea点击:

problems executing a jquery ajax call within a function

javascriptjqueryajax

提问by dwelch

I would like to put an ajax call within a function since I use it repeatedly in multiple locations. I want a manipulated version of the response returned. Here's what I'm trying to do (greatly simplified).

我想在一个函数中放置一个 ajax 调用,因为我在多个位置重复使用它。我想要返回的响应的操纵版本。这就是我想要做的(大大简化)。

a = getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
  $.ajax({
   type: "GET",
   url: 'someURL',
   success: function(response) {
     return response;
  });
}

What's happening, however, is that the append function is running before "a" has been defined in the getAjax function. Any thoughts?

然而,发生的情况是 append 函数在 getAjax 函数中定义“a”之前运行。有什么想法吗?

采纳答案by Niko

There are two ways to taggle this. one is to use the success callback:

有两种方法可以标记它。一种是使用成功回调:

$.ajax({
   type: "GET",
   url: 'someURL',
   success: function(response) {
     AppendResponse(response);
  });

the other is to set async to false http://api.jquery.com/jQuery.ajax/:

另一种是将 async 设置为 false http://api.jquery.com/jQuery.ajax/

var a;
getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
  $.ajax({
   type: "GET",
   url: 'someURL',
   async: false,
   success: function(response) {
     a = response;
  });
}

Important note on non async:

关于非异步的重要说明:

Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

跨域请求和 dataType: "jsonp" 请求不支持同步操作。

回答by lonesomeday

AJAX is asynchronous. This means that the code in the success handler is delayed until the request is successful, while the rest of the code continues as normal. You need to put the relevant code in the AJAX success handler:

AJAX 是异步的。这意味着成功处理程序中的代码会延迟到请求成功为止,而其余代码会照常继续。您需要将相关代码放在 AJAX 成功处理程序中:

getAjax();
function getAjax() {
  $.ajax({
   type: "GET",
   url: 'someURL',
   success: function(response) {
     $(document.body).append('<div>'+response+'</div>');
  });
}

Note that I have also optimised your bodyselector by using the native Javascript document.bodyrather than using the standard tag selector.

请注意,我还body使用本机 Javascriptdocument.body而不是使用标准标签选择器优化了您的选择器。



EditCallback version

编辑回调版本

function getAjax(callback) {
    $.ajax({
        type: 'GET',
        url: 'someURL',
        success: callback
    });
}

You can now do the code inline using a callback function:

您现在可以使用回调函数内联执行代码:

getAjax(function(response) {
    $(document.body).append('<div>'+response+'</div>');
});

or

或者

getAjax(function(response) {
    alert(response);
});

or whatever.

管他呢。

The code inside the anonymous function call will be processed when the AJAX request is complete.

当 AJAX 请求完成时,将处理匿名函数调用中的代码。

回答by dpmguise

One suggestion I have is to pass a trigger to the command you want to run into the AJAX function so that it will run after AJAX has received a response-

我的一个建议是将触发器传递给要运行到 AJAX 函数的命令,以便它在 AJAX 收到响应后运行 -

a = getAjax();
function getAjax() {
  $.ajax({
   type: "GET",
   url: 'someURL',
   success: function(response) {
     inputText(response);
  });
}

inputText(someText) {
$(document.body).append('<div>'+ someText +'</div>');
}

That way you can create if statements / other alternatives to continue to use the same AJAX command for different results

这样你就可以创建 if 语句/其他替代方案来继续使用相同的 AJAX 命令来获得不同的结果

回答by amurra

Why don't you return the response to another function in the success callback. This should handle your need for different responses:

为什么不在成功回调中将响应返回给另一个函数。这应该可以满足您对不同响应的需求:

getAjax();
function getAjax() {
  $.ajax({
   type: "GET",
   url: 'someURL',
   success: function(response) {
     AppendResponse(response);
  });
}

function AppendResponse(response) {
$('body').append('<div>'+response+'</div>');
}

回答by Rainer

You can give a handler to the function getAjax(), but if the user needs the information for the next decision then why not wait using async: false?

您可以为该函数提供一个处理程序getAjax(),但是如果用户需要下一个决定的信息,那么为什么不等待使用async: false呢?

function getAjax(handler) {
   $.ajax({
   type: "GET",
   url: 'someURL',
   success: function(response) {
     handler(response);
  });
};
function callGetAjax(response) {
  if(response === undefined) {
    getAjax(callGetAjax);
  } else {
    $('body').append('<div>'+response+'</div>');
  }
}