简体   繁体   English

AJAX成功响应文本

[英]AJAX response text for success

Right now I'm modifying my AJAX request to be asynchronous but I wanted to know if there was something similar to var reponse = $.ajax({ in success. Before I had my code as: 现在,我正在将我的AJAX请求修改为异步,但我想知道是否有类似于var reponse = $.ajax({的成功。在我获得如下代码之前:

     var response = $.ajax({
           type : "GET",
           url : url,
           data : parameters,
           cache : false,
           async : false
    }).responseText;

return response;

I tried doing using the first data argument but that just returns the parameters. 我尝试使用第一个数据参数来做,但这只是返回参数。 Is there something similar I can use in success? 我可以成功使用类似的东西吗?

success : function(response) {
     callBack(response); 
}

Because the request is asynchronous you cannot just return the response. 由于请求是异步的,因此您不能仅返回响应。

jQuery uses something called "promises", which you can return instead: jQuery使用一种叫做“ promises”的东西,您可以返回它:

function getUser(id) {
    return $.ajax({
        url: "/user",
        data: { id:id },
    });
}

So, whenever you want to get a user you just call the function: 因此,只要想获得用户,就只需调用该函数:

var userRequest = getUser(123);

The userRequest variable now contains a "future promise". 现在, userRequest变量包含“未来承诺”。 In other words, sometime in the future it will be ready for you to use it. 换句话说,将来的某个时候它将为您准备使用它。

You cannot use it straight away but you can create a function that will run when it finally is ready. 您不能立即使用它,但是可以创建一个在最终准备就绪时将运行的函数。 That is done using the .done() method: 这是使用.done()方法完成的:

userRequest.done(function (user) {
    console.log("The user " + user.name + " has been loaded!");
});

If you, for example, also want to load the user's profile alongside the user then you can create two requests and then use the $.when() method: 例如,如果您还希望将用户的个人资料加载到用户旁边,则可以创建两个请求,然后使用$.when()方法:

var userRequest    = getUser(123).
    profileRequest = getProfileForUser(123);

$.when(userRequest, profileRequest).done(function (user, profile) {
    console.log(user.name + " is " + profile.age + " years old");
});

Read more about promises over at jQuery . 在jQuery上阅读有关Promise的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM