热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

Ihaveasmallproblemwithjquery$.ajax()function.我对jquery$.ajax()函数有一个小问题。Ihaveaformwher

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

#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调用中错误。


推荐阅读
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • Servlet多用户登录时HttpSession会话信息覆盖问题的解决方案
    本文讨论了在Servlet多用户登录时可能出现的HttpSession会话信息覆盖问题,并提供了解决方案。通过分析JSESSIONID的作用机制和编码方式,我们可以得出每个HttpSession对象都是通过客户端发送的唯一JSESSIONID来识别的,因此无需担心会话信息被覆盖的问题。需要注意的是,本文讨论的是多个客户端级别上的多用户登录,而非同一个浏览器级别上的多用户登录。 ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文介绍了南邮ctf-web的writeup,包括签到题和md5 collision。在CTF比赛和渗透测试中,可以通过查看源代码、代码注释、页面隐藏元素、超链接和HTTP响应头部来寻找flag或提示信息。利用PHP弱类型,可以发现md5('QNKCDZO')='0e830400451993494058024219903391'和md5('240610708')='0e462097431906509019562988736854'。 ... [详细]
  • 本文介绍了在MFC下利用C++和MFC的特性动态创建窗口的方法,包括继承现有的MFC类并加以改造、插入工具栏和状态栏对象的声明等。同时还提到了窗口销毁的处理方法。本文详细介绍了实现方法并给出了相关注意事项。 ... [详细]
  • GreenDAO快速入门
    前言之前在自己做项目的时候,用到了GreenDAO数据库,其实对于数据库辅助工具库从OrmLite,到litePal再到GreenDAO,总是在不停的切换,但是没有真正去了解他们的 ... [详细]
  • 如何在php文件中添加图片?
    本文详细解答了如何在php文件中添加图片的问题,包括插入图片的代码、使用PHPword在载入模板中插入图片的方法,以及使用gd库生成不同类型的图像文件的示例。同时还介绍了如何生成一个正方形文件的步骤。希望对大家有所帮助。 ... [详细]
  • web.py开发web 第八章 Formalchemy 服务端验证方法
    本文介绍了在web.py开发中使用Formalchemy进行服务端表单数据验证的方法。以User表单为例,详细说明了对各字段的验证要求,包括必填、长度限制、唯一性等。同时介绍了如何自定义验证方法来实现验证唯一性和两个密码是否相等的功能。该文提供了相关代码示例。 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • MySQL数据库锁机制及其应用(数据库锁的概念)
    本文介绍了MySQL数据库锁机制及其应用。数据库锁是计算机协调多个进程或线程并发访问某一资源的机制,在数据库中,数据是一种供许多用户共享的资源,如何保证数据并发访问的一致性和有效性是数据库必须解决的问题。MySQL的锁机制相对简单,不同的存储引擎支持不同的锁机制,主要包括表级锁、行级锁和页面锁。本文详细介绍了MySQL表级锁的锁模式和特点,以及行级锁和页面锁的特点和应用场景。同时还讨论了锁冲突对数据库并发访问性能的影响。 ... [详细]
  • Hibernate延迟加载深入分析-集合属性的延迟加载策略
    本文深入分析了Hibernate延迟加载的机制,特别是集合属性的延迟加载策略。通过延迟加载,可以降低系统的内存开销,提高Hibernate的运行性能。对于集合属性,推荐使用延迟加载策略,即在系统需要使用集合属性时才从数据库装载关联的数据,避免一次加载所有集合属性导致性能下降。 ... [详细]
  • 微信官方授权及获取OpenId的方法,服务器通过SpringBoot实现
    主要步骤:前端获取到code(wx.login),传入服务器服务器通过参数AppID和AppSecret访问官方接口,获取到OpenId ... [详细]
author-avatar
王立君淑霖_189
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有