jquery——成功时使用ajax返回值

时间:2022-09-15 12:05:54

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个选项-第一个(无标签)有一个值=""其他有他们的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.

我希望发生的是没有一个选项(与空白值)将创建一个会话和其他,但只有当与这个特定的会话选择名称不存在——正如所有其他选项有相同的金额分配给它,它只是表明哪一个被选中。

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选择菜单触发“change”时,我们从一些元素中获得一些值用于计算。

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.

我们从select中获取选项的label属性,该属性存储要添加到total的值,选择要创建具有此名称的会话的名称,以及用于稍后检查所选择的值。

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 = ""(这将表明没有选择选项),并从总数中扣除金额,并删除带有select名称的会话。

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然后加入总值存储在标签属性,但如果它返回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”是否会返回函数的结果——因为它似乎不起作用——但是,如果我将“data”放在success: section中——它似乎返回了正确的值。

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; }

函数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?

但出于某种原因——它不起作用——有什么想法吗?

7 个解决方案

#1


89  

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 inside the success: callback. That way it is accessing the data only when it is available.

这个问题的解决方案是在success: callback中运行必要的代码。这样,它只能在数据可用时访问数据。

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
}

#2


27  

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

有很多方法可以获得jQuery AJAX响应。我想和大家分享两个常见的方法:

First:

第一:

use async=false and 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 $.extend method and make a new function like ajax

使用美元。扩展方法并创建一个新的函数,如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...

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

#3


5  

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

阿纳金

#4


3  

Add async: false to 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线程在获取返回值之前等待。显然,您不会希望在每种情况下都这样做,但是如果在继续之前需要一个值,那么这就可以了。

#5


2  

This is quite old, and ugly, don't do this. You should use callbacks: https://*.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://*.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;
}

#6


1  

// 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调用成功时调用的函数,这可能会有所帮助,请参见示例

#7


0  

Hi try async:false in your ajax call..

尝试异步:在ajax调用中错误。

#1


89  

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 inside the success: callback. That way it is accessing the data only when it is available.

这个问题的解决方案是在success: callback中运行必要的代码。这样,它只能在数据可用时访问数据。

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
}

#2


27  

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

有很多方法可以获得jQuery AJAX响应。我想和大家分享两个常见的方法:

First:

第一:

use async=false and 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 $.extend method and make a new function like ajax

使用美元。扩展方法并创建一个新的函数,如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...

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

#3


5  

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

阿纳金

#4


3  

Add async: false to 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线程在获取返回值之前等待。显然,您不会希望在每种情况下都这样做,但是如果在继续之前需要一个值,那么这就可以了。

#5


2  

This is quite old, and ugly, don't do this. You should use callbacks: https://*.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://*.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;
}

#6


1  

// 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调用成功时调用的函数,这可能会有所帮助,请参见示例

#7


0  

Hi try async:false in your ajax call..

尝试异步:在ajax调用中错误。