在函数内执行jquery ajax调用时出现问题 [英] problems executing a jquery ajax call within a function

查看:52
本文介绍了在函数内执行jquery ajax调用时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将ajax调用放入函数中,因为我在多个位置重复使用了它.我想要返回响应的操纵版本.这就是我正在尝试做的事情(大大简化了).

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).

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

但是,正在发生的事情是,在getAjax函数中定义了"a"之前,append函数正在运行.有什么想法吗?

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

推荐答案

可以通过两种方式对此进行标记.一种是使用成功回调:

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

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

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

the other is to set async to 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:

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

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

这篇关于在函数内执行jquery ajax调用时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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