jQuery-成功使用Ajax结果返回值 [英] jquery - return value using ajax result on success

查看:82
本文介绍了jQuery-成功使用Ajax结果返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

现在-我有一个下拉菜单,其中有4个选项-第一个(标签为None)具有value =",其他具有其ID.

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.

我要执行的操作是使用None选项(具有空白值)删除会话,并使用其他选项创建会话,但前提是该特定选择名称的会话尚不存在-因为所有其他选项的数量相同分配给它-只是表明选择了哪个.

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

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

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

我们从选择中获得选项的标签属性,该选择存储将要添加到总数中的值,选择的名称(使用此名称创建会话)和值,以供以后检查选择了哪个.

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.

现在-我们检查val =="(这表明已选择无"选项),然后从总数中扣除金额,并删除具有选择名称的会话.

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.

这是问题开始的地方-else语句.

After this is where the problem starts - else statement.

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

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函数看起来像这样:

Now isSession function looks like this:

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

现在-问题是-我不知道使用"return"是否会从函数中返回结果-因为它似乎不起作用-但是,如果我将"data"放在成功的位置:部分进入警报-它似乎确实返回了正确的值.

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.

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

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

然后使用updateResult()函数:

then the updateResult() function:

function updateResult(data){ 结果=数据; }

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?

推荐答案

问题是您无法从异步调用(如AJAX请求)中返回一个值,并希望它能正常工作.

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

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

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

此问题的解决方案是在success:回调中的内部中运行必需的代码.这样,它仅在data可用时对其进行访问.

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.

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

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

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.

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
}

这篇关于jQuery-成功使用Ajax结果返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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