jquery - 成功时使用ajax结果返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3302702/
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-26 15:12:12  来源:igfitidea点击:

jquery - return value using ajax result on success

jquery

提问by user398341

I have a small problem with jquery $.ajax() function.

jquery $.ajax() 函数有一个小问题。

I have a form where every click on the radio button or selection from the dropdown menu creates a session variable with the selected value.

我有一个表单,每次单击单选按钮或从下拉菜单中进行选择都会创建一个具有所选值的会话变量。

Now - I have one of the dropdown menus which have 4 options - the first one (with label None) has a value="" other have their ids.

现在 - 我有一个下拉菜单,其中有 4 个选项 - 第一个(带有标签 None)有一个 value="" 其他有他们的 id。

What I want to happen is to None option (with blank value) to remove the session and other to create one, but only if session with this specific select name doesn't already exist - as all other options have the same amount assigned to it - it's just indicating which one was selected.

我想要发生的是 None 选项(带有空白值)删除会话和其他创建一个,但前提是具有此特定选择名称的会话尚不存在 - 因为所有其他选项都分配了相同的数量- 这只是表明选择了哪一个。

I'm not sure if that makes sense - but have a look at the code - perhaps this will make it clearer:

我不确定这是否有意义 - 但看看代码 - 也许这会让它更清楚:

$("#add_ons select").change(function() {
        // get current price of the addons
        var order_price_addon = $(".order_price_addon").text();
        // get price of the clicked radio button from the rel attribute
        var add = $(this).children('option').attr('label');
        var name = $(this).attr('name');
        var val = $(this).val();


        if(val == "") {
            var price = parseInt(order_price_addon) - parseInt(add);
            removeSession(name);
        } else {
            if(isSession(name) == 0) {
                var price = parseInt(order_price_addon) + parseInt(add);
            }   
            setSession(name, val);              
        }

        $(".order_price_addon").html(price);    
        setSession('order_price_addon', price);         
        updateTotal();
});

so - first of all when the #add_ons select menu triggers "change" we get some values from a few elements for calculations.

所以 - 首先,当 #add_ons 选择菜单触发“更改”时,我们从几个元素中获取一些值进行计算。

we get the label attribute of the option from our select which stores the value to be added to the total, name of the select to create session with this name and value to later check which one was selected.

我们从我们的选择中获取选项的标签属性,该属性存储要添加到总数中的值、选择的名称以使用此名称创建会话以及稍后检查选择了哪个值。

now - we check whether the val == "" (which would indicate that None option has been selected) and we deduct the amount from the total as well as remove the session with the select's name.

现在 - 我们检查是否 val == "" (这表示已选择 None 选项),我们从总数中扣除金额,并删除具有选择名称的会话。

After this is where the problem starts - else statement.

在这之后就是问题开始的地方 - else 语句。

Else - we want to check whether the isSession() function with the name of our selector returns 0 or 1 - if it returns 0 then we add to the total the value stored in the label attribute, but if it returns 1 - that would suggest that session already exists - then we only change the value of this session by recreating it - but the amount isn't added to it.

否则 - 我们想要检查带有我们选择器名称的 isSession() 函数是否返回 0 或 1 - 如果它返回 0 那么我们将存储在 label 属性中的值添加到总数中,但如果它返回 1 - 这将表明该会话已经存在 - 然后我们只通过重新创建它来更改该会话的值 - 但不会添加数量。

Now isSession function looks like this:

现在 isSession 函数看起来像这样:

function isSession(selector) {
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        success: function(data) {
            return data;
        },
        error: function() {
            alert('Error occured');
        }
    });
}

Now - the problem is - that I don't know whether using "return" will return the result from the function - as it doesn't seem to work - however, if I put the "data" in the success: section into the alert - it does seem to return the right value.

现在 - 问题是 - 我不知道使用“return”是否会从函数返回结果 - 因为它似乎不起作用 - 但是,如果我将“数据”放在成功:部分到警报 - 它似乎确实返回了正确的值。

Does anyone know how to return the value from the function and then compare it in the next statement?

有谁知道如何从函数返回值,然后在下一个语句中进行比较?



Thanks guys - I've tried it in the following way:

谢谢你们 - 我已经通过以下方式尝试过:

function isSession(selector) {
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        success: function(data) {
            updateResult(data);
        },
        error: function() {
            alert('Error occured');
        }
    });
}

then the updateResult() function:

然后是 updateResult() 函数:

function updateResult(data) { result = data; }

函数更新结果(数据){ 结果 = 数据;}

result - is the global variable - which I'm then trying to read:

结果 - 是全局变量 - 然后我试图阅读:

$("#add_ons select").change(function() {
        // get current price of the addons
        var order_price_addon = $(".order_price_addon").text();
        // get price of the clicked radio button from the rel attribute
        var add = $(this).children('option').attr('label');
        var name = $(this).attr('name');
        var val = $(this).val();


        if(val == "") {
            var price = parseInt(order_price_addon) - parseInt(add);
            removeSession(name);
        } else {
            isSession(name);
            if(result == 0) {
                var price = parseInt(order_price_addon) + parseInt(add);
            }   
            setSession(name, val);              
        }

        $(".order_price_addon").html(price);    
        setSession('order_price_addon', price);         
        updateTotal();
    });

but for some reason - it doesn't work - any idea?

但出于某种原因 - 它不起作用 - 知道吗?

回答by user113716

The trouble is that you can not return a value from an asynchronous call, like an AJAX request, and expect it to work.

问题是您无法从异步调用(如 AJAX 请求)返回值,并期望它能够工作。

The reason is that the code waiting for the response has already executed by the time the response is received.

原因是等待响应的代码在收到响应时已经执行了。

The solution to this problem is to run the necessary code insidethe success:callback. That way it is accessing the dataonly when it is available.

这个问题的解决方案是运行所需的代码success:回调。这样它data只会在可用时访问。

function isSession(selector) {
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        success: function(data) {
            // Run the code here that needs
            //    to access the data returned
            return data;
        },
        error: function() {
            alert('Error occured');
        }
    });
}

Another possibility (which is effectively the same thing) is to call a function inside your success:callback that passes the data when it is available.

另一种可能性(实际上是同一件事)是在success:回调中调用一个函数,该函数在数据可用时传递数据。

function isSession(selector) {
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        success: function(data) {
                // Call this function on success
            someFunction( data );
            return data;
        },
        error: function() {
            alert('Error occured');
        }
    });
}

function someFunction( data ) {
    // Do something with your data
}

回答by Neeraj Singh

There are many ways to get jQuery AJAX response. I am sharing with you two common approaches:

有很多方法可以获得 jQuery AJAX 响应。我与您分享两种常见的方法:

First:

第一的:

use async=falseand within function return ajax-object and later get response ajax-object.responseText

使用async=false并在函数内返回 ajax-object 并稍后获得响应 ajax-object.responseText

/**
 * jQuery ajax method with async = false, to return response
 * @param  {mix}  selector - your selector
 * @return {mix}           - your ajax response/error
 */
function isSession(selector) {
    return $.ajax({
        type: "POST",
        url: '/order.html',
        data: {
            issession: 1,
            selector: selector
        },
        dataType: "html",
        async: !1,
        error: function() {
            alert("Error occured")
        }
    });
}
// global param
var selector = !0;
// get return ajax object
var ajaxObj = isSession(selector);
// store ajax response in var
var ajaxResponse = ajaxObj.responseText;
// check ajax response
console.log(ajaxResponse);
// your ajax callback function for success
ajaxObj.success(function(response) {
    alert(response);
});

Second:

第二:

use $.extendmethod and make a new function like ajax

使用$.extend方法并创建一个像 ajax 这样的新函数

/**
 * xResponse function
 *
 * xResponse method is made to return jQuery ajax response
 * 
 * @param  {string} url   [your url or file]
 * @param  {object} your ajax param
 * @return {mix}       [ajax response]
 */
$.extend({
    xResponse: function(url, data) {
        // local var
        var theResponse = null;
        // jQuery ajax
        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            dataType: "html",
            async: false,
            success: function(respText) {
                theResponse = respText;
            }
        });
        // Return the response text
        return theResponse;
    }
});

// set ajax response in var
var xData = $.xResponse('temp.html', {issession: 1,selector: true});

// see response in console
console.log(xData);

you can make it as large as you want...

你可以把它做成你想要的大小......

回答by anakin

I saw the answers here and although helpful, they weren't exactly what I wanted since I had to alter a lot of my code.

我在这里看到了答案,虽然很有帮助,但它们并不是我想要的,因为我不得不修改很多代码。

What worked out for me, was doing something like this:

对我有用的是做这样的事情:

function isSession(selector) {
    //line added for the var that will have the result
    var result = false;
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        //line added to get ajax response in sync
        async: false,
        success: function(data) {
            //line added to save ajax response in var result
            result = data;
        },
        error: function() {
            alert('Error occured');
        }
    });
    //line added to return ajax response
    return result;
}

Hope helps someone

希望能帮助某人

anakin

阿纳金

回答by MR_AMDEV

Although all the approaches regarding the use of async: falseare not good because of its deprecation and stuck the page untill the request comes back. Thus here are 2 ways to do it:

虽然所有关于使用的async: false方法都不好,因为它被弃用了,并且在请求回来之前卡住了页面。因此,这里有两种方法可以做到:

1st: Return whole ajax response in a function and then make use of donefunction to capture the response when the request is completed.(RECOMMENDED, THE BEST WAY)

第一:在一个函数中返回整个ajax响应,然后done在请求完成时使用函数来捕获响应。(推荐,最好的方法)

function getAjax(url, data){
    return $.ajax({
        type: 'POST',
        url : url,              
        data: data,
        dataType: 'JSON',
        //async: true,  //NOT NEEDED
        success: function(response) {
            //Data = response;
        }
    });
 }

CALL THE ABOVE LIKE SO:

像这样调用上面的:

getAjax(youUrl, yourData).done(function(response){
    console.log(response);
});

FOR MULTIPLE AJAX CALLS MAKE USE OF $.when:

对于多个 AJAX 调用,请使用$.when

$.when( getAjax(youUrl, yourData), getAjax2(yourUrl2, yourData2) ).done(function(response){
    console.log(response);
});

2nd: Store the response in a cookie and then outside of the ajax call get that cookie value.(NOT RECOMMENDED)

第二:将响应存储在 cookie 中,然后在 ajax 调用之外获取该 cookie 值。(不推荐)

        $.ajax({
            type: 'POST',
            url : url,              
            data: data,
            //async: false,    // No need to use this
            success: function(response) {
                Cookies.set(name, response);
            }
        });

        // Outside of the ajax call
        var response = Cookies.get(name);

NOTE:In the exmple above jquery cookieslibrary is used.It is quite lightweight and works as snappy. Here is the link https://github.com/js-cookie/js-cookie

注意:在上面的例子中使用了jquery cookies库。它非常轻巧,工作起来很活泼。这是链接https://github.com/js-cookie/js-cookie

回答by Hoodlum

Add async: falseto your attributes list. This forces the javascript thread to wait until the return value is retrieved before moving on. Obviously, you wouldn't want to do this in every circumstance, but if a value is needed before proceeding, this will do it.

添加async: false到您的属性列表。这会强制 javascript 线程在继续之前等待直到检索到返回值。显然,您不会希望在每种情况下都这样做,但如果在继续之前需要一个值,则可以这样做。

回答by aesede

This is quite old, and ugly, don't do this. You should use callbacks: https://stackoverflow.com/a/5316755/591257
Had same problem, solved it this way, using a global var. Not sure if it's the best but surely works. On error you get an empty string (myVar = ''), so you can handle that as needed.

这很旧,而且很丑,不要这样做。您应该使用回调:https: //stackoverflow.com/a/5316755/591257
有同样的问题,使用全局变量以这种方式解决。不确定它是否是最好的,但肯定有效。出错时,您会得到一个空字符串 (myVar = ''),因此您可以根据需要进行处理。

var myVar = '';
function isSession(selector) {
  $.ajax({
    'type': 'POST',
    'url': '/order.html',
    'data': {
      'issession': 1,
      'selector': selector
    },
    'dataType': 'html',
    'success': function(data) {
      myVar = data;
    },
    'error': function() {
      alert('Error occured');
    }
  });
  return myVar;
}

回答by Binson

// Common ajax caller
function AjaxCall(url,successfunction){
  var targetUrl=url;
  $.ajax({
    'url': targetUrl,
    'type': 'GET',
    'dataType': 'json',
    'success': successfunction,
    'error': function() {
      alert("error");
    }
  });
}

// Calling Ajax
$(document).ready(function() {
  AjaxCall("productData.txt",ajaxSuccessFunction);
});

// Function details of success function
function ajaxSuccessFunction(d){
  alert(d.Pioneer.Product[0].category);
}

it may help, create a common ajax call function and attach a function which invoke when success the ajax call, see the example

它可能会有所帮助,创建一个通用的 ajax 调用函数并附加一个函数,该函数在成功调用 ajax 时调用,请参见示例

回答by Muhammad Nahid

With Help from here

这里得到帮助

function get_result(some_value) {
   var ret_val = {};
   $.ajax({
       url: '/some/url/to/fetch/from,
       type: 'GET',
       data: {'some_key': some_value},
       async: false,
       dataType: 'json'
   }).done(function (response) {
       ret_val = response;
   }).fail(function (jqXHR, textStatus, errorThrown) {
           ret_val = null;
       });
   return ret_val;
}

Hope this helps someone somewhere a bit.

希望这对某人有所帮助。

回答by kathir

Hi try async:falsein your ajax call..

嗨,在您的 ajax 调用中尝试async:false..