jQuery:将Ajax调用的值返回给调用者函数? [英] Jquery: Return the value of a ajax call to caller function?

查看:70
本文介绍了jQuery:将Ajax调用的值返回给调用者函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从函数返回$ ajax调用返回的值,但仅返回未定义".如果警报来自ajax调用的响应",它将返回rigth值.这是代码,我在做什么错了?:

Im trying to return the value that a $ajax call returns, from a function but it only returns "undefined". If a alert the "reponse" from the ajax call it returns the rigth value. Here is the code, what am i doing wrong?:

$(".insertCandidate").live("click", (function(e) {
            var ids = this.id.toString().split("|");
            var tempCanID = ids[1];
            var canID = ids[0];
            var tempName = CandidateName(tempCanID);
            var canName = CandidateName(canID);
            //alert("HTML: "+tempName);
            $("#mergeCandidateDialog").empty();
            $.blockUI({ message: $("#mergeCandidateDialog").append(
                "<div>" + tempName + "s ansøgning til vil blive lagt under den eksiterende ansøger s data.<br /><br /> Ønsker du at fortsætte?<br /><br /></div>" +
                "<div id=\"content\">" +
                "<input type=\"button\" id=\"" + ids + "\" class=\"insertCandidateYes\" value=\"Ja\" />" +
                "<input type=\"button\" id=\"insertCandidateNo\" value=\"Nej\" /></div>"), css: { cursor: 'default', fontWeight: 'normal', padding: '7px', textAlign: 'left' }
            });
        }));

function CandidateName(candidateID) {
        var returnstring;
        $.ajax({
            type: "POST",
            url: "/Admin/GetCandidateName/",
            data: { 'candidateID': candidateID },
            succes: function(response) {
                returnstring = response;
                return;
            },
            error: function(response) {
                alert("FEJL: " + response);
            }
        });

        return returnstring;
    }

推荐答案

除非您使用asynch:false等待ajax调用完成,否则您将无法执行此操作.但是我不会这样做,因为它会锁定浏览器,并且如果调用失败返回,用户将不得不崩溃.最好在.ajax调用的成功函数中重构脚本并调用回调函数.

You cannot do this unless you wait for the ajax call to complete by using asynch:false. However I would not do this as it locks up the browser and if the call fails to return the user will have to crash out. It is better to refactor your script and within the success function of the .ajax call to invoke a callback function.

请参阅我对类似问题的回答这里

See my answer to a similar question here

这篇关于jQuery:将Ajax调用的值返回给调用者函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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