将 jQuery ajax 响应文本分配给变量常量返回 null

发布于 2024-10-11 01:04:18 字数 1060 浏览 9 评论 0原文

希望这个伟大网站上的其中一位能够提供帮助。我在将变量分配给 jQuery ajax 调用响应文本时遇到问题。

我有一个表单,提交后会运行我的“checkemail”功能来验证可以在数据库中找到电子邮件地址。如果找到,则responseText ==“true”,否则为“false”。这工作正常,并且可以使用 Firebug 看到它。但是响应文本应该分配给的实际变量不断显示“”,因此导致函数始终返回 false。

        function checkemail(){

            var EmailFromForm = $("#lostemail").val();

            var EmailCheckRes = $.ajax({

            type        : "POST",
            cache       : false,
            url         : "./scripts/passreset/emailcheck.php",
            data        : "Email="+EmailFromForm,
            dataType        : "text",

      }).responseText;


            if (EmailCheckRes == "true")
            {
                alert("Should say true:  " + EmailCheckRes);
                return true;
            }
            else
            {
                $("#ErrorMsg").html("Your email address is either invalid or not found.");
                alert("Should say false:  " + EmailCheckRes);
                return false;
            }   

        }   

如果有人对我做错了什么有任何指示,我将不胜感激。

hopefully one of you on this great site can help. I'm having issues with assigning a variable to a jQuery ajax call response text.

I have a form which when submited runs my "checkemail" function to varify the email address can be found in a database. If it's found, the responseText == "true", else "false". This works fine, and can be seen ok using Firebug....but the actual variable the response text should be assigned to is constantly showing "", and therefore causing the function to return false all the time.

        function checkemail(){

            var EmailFromForm = $("#lostemail").val();

            var EmailCheckRes = $.ajax({

            type        : "POST",
            cache       : false,
            url         : "./scripts/passreset/emailcheck.php",
            data        : "Email="+EmailFromForm,
            dataType        : "text",

      }).responseText;


            if (EmailCheckRes == "true")
            {
                alert("Should say true:  " + EmailCheckRes);
                return true;
            }
            else
            {
                $("#ErrorMsg").html("Your email address is either invalid or not found.");
                alert("Should say false:  " + EmailCheckRes);
                return false;
            }   

        }   

If anyone has any pointers as to what i'm doing wrong it'd be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

℡寂寞咖啡 2024-10-18 01:04:18

问题是 $.ajax 方法异步执行,因此 checkemail 函数在 ajax 请求完成之前返回。

您的应用程序流程不是线性的,因此您的 checkmail 返回值不会反映您的 ajax 请求返回的响应。

您需要重构代码以接受回调并在 ajax 请求完成时执行它。

The problem is that the $.ajax method is getting executed async so the checkemail function is returning before your ajax request is completed.

The flow of your application is not linear and therefore your return value from checkmail will not reflect the response returned from your ajax request.

You'll need to restructure your code to take a callback and execute it when your ajax request is complete.

这样的小城市 2024-10-18 01:04:18

您的 ajax url 需要是 emailcheck.php 的 Web url,而不是使用 ./

var EmailCheckRes = $.ajax({

    type        : "POST",
    cache       : false,
    async       : false,
    url         : "scripts/passreset/emailcheck.php",
    data        : "Email="+EmailFromForm,
    dataType    : "text",

    }).responseText;

编辑: 的相对系统路径,虽然它不是最佳选择要切换到同步服务器请求的解决方案,您可能只需设置 ajax 选项 async: false ,这将使浏览器等待响应继续,这应该可以消除您的问题。另外,我建议切换到绝对路径,和/或从相对路径前面删除 ./ 。我已将此选项添加到我的示例代码中。

your ajax url needs to be the web url of emailcheck.php not a relative system path using ./

var EmailCheckRes = $.ajax({

    type        : "POST",
    cache       : false,
    async       : false,
    url         : "scripts/passreset/emailcheck.php",
    data        : "Email="+EmailFromForm,
    dataType    : "text",

    }).responseText;

EDIT : While it is not the optimal solution to switch to a synchronous server request, you might just set the ajax option async: false which will make the browser wait for the response to continue, which should eliminate your issue. Also I would recommend switching to an absolute path, and/or removing the ./ from the front of your relative path. I have reflected this option addition to my example code.

情何以堪。 2024-10-18 01:04:18

您需要重构您的代码。大多数 AJAX 调用都是异步的,这意味着代码流无需等待调用完成即可进行。

有意义的是,您需要更改:

function checkmail() {
    var checkThis = Ajax();

    if (checkThis) {
        DoSomething();
    }
    else {
        DontDoSomething();
    }
}

for:

function checkmail() {
    Ajax.success = function(checkThis){
        if (checkThis) {
            DoSomething();
        }
        else {
            DontDoSomething();
        }
    };

    Ajax.error= function(){
        ReportSomeError();
    };

    Ajax();
}

应用于您的代码,它可能会像这样:

function checkemail () {
    var EmailFromForm = $("#lostemail").val(),

    $.ajax({
        type:"POST",
        cache:false,
        url:"./scripts/passreset/emailcheck.php",
        data:"Email="+EmailFromForm,
        dataType:"text",
        success:function(EmailCheckRes){
            if (EmailCheckRes == "true") {
                alert("Should say true:  " + EmailCheckRes);

                /* You cannot longer "return" this value, add code to do
                 * what you need done
                 */
                return true;
            }
            else {
                $("#ErrorMsg").html("Your email address is either invalid or not found.");
                alert("Should say false:  " + EmailCheckRes);

                /* You cannot longer "return" this value, add code to do
                 * what you need done
                 */
                return false;
            }
        },
        error:function(){
            $("#ErrorMsg").html("There was an AJAX communication error.");
        }
    });
}

You need to restructure your code. Most of the AJAX calls are async, meaning the flow of the code goes without waiting for the call to be completed.

Meaningfully, you need to change:

function checkmail() {
    var checkThis = Ajax();

    if (checkThis) {
        DoSomething();
    }
    else {
        DontDoSomething();
    }
}

for:

function checkmail() {
    Ajax.success = function(checkThis){
        if (checkThis) {
            DoSomething();
        }
        else {
            DontDoSomething();
        }
    };

    Ajax.error= function(){
        ReportSomeError();
    };

    Ajax();
}

Applied to your code, it may go something like this:

function checkemail () {
    var EmailFromForm = $("#lostemail").val(),

    $.ajax({
        type:"POST",
        cache:false,
        url:"./scripts/passreset/emailcheck.php",
        data:"Email="+EmailFromForm,
        dataType:"text",
        success:function(EmailCheckRes){
            if (EmailCheckRes == "true") {
                alert("Should say true:  " + EmailCheckRes);

                /* You cannot longer "return" this value, add code to do
                 * what you need done
                 */
                return true;
            }
            else {
                $("#ErrorMsg").html("Your email address is either invalid or not found.");
                alert("Should say false:  " + EmailCheckRes);

                /* You cannot longer "return" this value, add code to do
                 * what you need done
                 */
                return false;
            }
        },
        error:function(){
            $("#ErrorMsg").html("There was an AJAX communication error.");
        }
    });
}
小红帽 2024-10-18 01:04:18

在事件的“document.ready”阶段,我确实很难将 jQuery ajax 的结果放入我的变量中。

当用户在页面加载后触发选择框的“onchange”事件时,jQuery 的 ajax 会加载到我的变量中,但在页面首次加载时数据不会提供给变量。

我尝试了很多很多不同的方法,但最终,我需要的答案就在这个 stackoverflow 页面: JQuery - 将 ajax 响应存储到全局变量中

感谢贡献者 Charles Guilbert,即使我的页面首次加载,我也能够将数据获取到我的变量中。

这是工作脚本的示例:

jQuery.extend
(
    {
        getValues: function(url) 
        {
            var result = null;
            $.ajax(
                {
                    url: url,
                    type: 'get',
                    dataType: 'html',
                    async: false,
                    cache: false,
                    success: function(data) 
                    {
                        result = data;
                    }
                }
            );
           return result;
        }
    }
);

// Option List 1, when "Cats" is selected elsewhere
optList1_Cats += $.getValues("/MyData.aspx?iListNum=1&sVal=cats");

// Option List 1, when "Dogs" is selected elsewhere
optList1_Dogs += $.getValues("/MyData.aspx?iListNum=1&sVal=dogs");

// Option List 2, when "Cats" is selected elsewhere
optList2_Cats += $.getValues("/MyData.aspx?iListNum=2&sVal=cats");

// Option List 2, when "Dogs" is selected elsewhere
optList2_Dogs += $.getValues("/MyData.aspx?iListNum=2&sVal=dogs");

I really struggled with getting the results of jQuery ajax into my variables at the "document.ready" stage of events.

jQuery's ajax would load into my variables when a user triggered an "onchange" event of a select box after the page had already loaded, but the data would not feed the variables when the page first loaded.

I tried many, many, many different methods, but in the end, the answer I needed was at this stackoverflow page: JQuery - Storing ajax response into global variable

Thanks to contributor Charles Guilbert, I am able to get data into my variables, even when my page first loads.

Here's an example of the working script:

jQuery.extend
(
    {
        getValues: function(url) 
        {
            var result = null;
            $.ajax(
                {
                    url: url,
                    type: 'get',
                    dataType: 'html',
                    async: false,
                    cache: false,
                    success: function(data) 
                    {
                        result = data;
                    }
                }
            );
           return result;
        }
    }
);

// Option List 1, when "Cats" is selected elsewhere
optList1_Cats += $.getValues("/MyData.aspx?iListNum=1&sVal=cats");

// Option List 1, when "Dogs" is selected elsewhere
optList1_Dogs += $.getValues("/MyData.aspx?iListNum=1&sVal=dogs");

// Option List 2, when "Cats" is selected elsewhere
optList2_Cats += $.getValues("/MyData.aspx?iListNum=2&sVal=cats");

// Option List 2, when "Dogs" is selected elsewhere
optList2_Dogs += $.getValues("/MyData.aspx?iListNum=2&sVal=dogs");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文