Jquery: Return the value of a ajax call to caller function?

后端 未结 4 596
醉酒成梦
醉酒成梦 2021-01-27 15:53

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 va

相关标签:
4条回答
  • 2021-01-27 16:40

    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

    0 讨论(0)
  • 2021-01-27 16:41
     $.ajax({
            type: "POST",
            url: "/Admin/GetCandidateName/",
            data: { 'candidateID': candidateID },
            success: function(response) {
                return response;//USE THIS
    
                //THIS WILL RETURN FROM THE FUNCTION WITHOUT RETURNING ANY VALUE
                //return;
            },
    
    0 讨论(0)
  • 2021-01-27 16:47

    You're doing 2 ajax requests which are identical. To improve performance you should pass an array of IDs to your CandidateName method and then your server-side script also should return an array of matched names.

    0 讨论(0)
  • 2021-01-27 16:48

    Add an async true attribute to your .ajax call:

        type: "POST",
        async: false, // ADD THIS
        url: "/Admin/GetCandidateName/",
    

    Also, you left off an "s" on success.

    That may do it.

    0 讨论(0)
提交回复
热议问题