简体   繁体   English

使用jQuery $ .ajax进行Javascript范围查询

[英]Javascript scoping query using jQuery $.ajax

I am trying to write simple function that checks to see if a designer name exists in the database. 我正在尝试编写简单的函数来检查数据库中是否存在设计器名称。 I am using jQuery's ajax function to try to do this: 我正在使用jQuery的ajax函数来尝试执行此操作:

function checkDesignerName(name)
{   
    var designer_name = $('input[name="name"]').val();
    var designer_exists =  false;
    var temp = $.ajax( { type: "GET", 
             url: "/api/check_brand_exists/", 
             data : {name : designer_name }, 
             success: function(data) {
                    designer_exists = $.parseJSON(data);
                    return designer_exists;
                }}).statusText;
    return designer_exists;
}

I have read about javascript scoping, and but still can't seem to find my bug, which is checkDesignerName always returns false. 我已经阅读了有关javascript作用域的知识,但似乎仍然找不到我的错误,因为checkDesignerName总是返回false。 Do I need to use a closure for this function to work correctly? 我是否需要使用闭包功能才能正常工作?

Thanks 谢谢

It's the nature of AJAX which is asynchronous that you seem to have troubles with understanding. 这是异步的AJAX的本质,您似乎难以理解。

At this stage: 在这个阶段:

return designer_exists;

your AJAX call hasn't yet finished. 您的AJAX通话尚未结束。 It's only inside the success callback, which happens much later, that you can use the results. 只有在成功回调(稍后发生)中,您才可以使用结果。 You cannot have a function which returns some result and this result depends on an AJAX call. 您不能具有返回某些结果的函数,并且该结果取决于AJAX调用。 You can only exploit the results of an AJAX call iniside the success callback: 您只能在成功回调中利用AJAX调用的结果:

function checkDesignerName(name)
{   
    var designer_name = $('input[name="name"]').val();
    $.ajax({ 
        type: "GET", 
        url: "/api/check_brand_exists/", 
        data : { name : designer_name }, 
        success: function(data) {
            var designer_exists = $.parseJSON(data);
            // Here and only here you know whether this designer exists
            alert(designer_exists);
        }
    });
}

You could of course perform a synchronous call to the server which is something totally not recommended as it will freeze the client browser and piss the user off your site during the AJAX request by setting the async: false flag: 您当然可以执行对服务器的同步调用,这是完全不推荐的操作,因为它会冻结客户端浏览器,并在AJAX请求期间通过设置async: false标志将用户惹恼您的站点。

function checkDesignerName(name)
{   
    var designer_name = $('input[name="name"]').val();
    var designer_exists = false;
    $.ajax({ 
        type: "GET", 
        url: "/api/check_brand_exists/", 
        async: false,
        data : { name : designer_name }, 
        success: function(data) {
            designer_exists = $.parseJSON(data);
        }
    });
    return designer_exists;
}

I am mentioning this just for completeness of the answer, not as something that you should ever be doing. 我提到这仅仅是为了完整答案,而不是您应该做的事情。

Now because it seems that you are doing some kind of validation logic here, here's what I would recommend you as an ultimate solution: the jquery.validate plugin . 现在,由于您似乎在此处执行某种验证逻辑,因此,我向您推荐这是最终解决方案: jquery.validate plugin It has this great remote rule support that will do exactly what you need here. 它具有强大的远程规则支持,可以完全满足您的需求。

$.ajax is a async call. $ .ajax是异步调用。 It means the statement return designer_exists gets executed even before success function is executed. 这意味着即使在执行成功功能之前,语句return designer_exists也会被执行。 That is the reason it always returns false. 这就是它总是返回false的原因。

  1. your success function don't see designer_exists variable 您的成功函数看不到designer_exists变量
  2. return action runs before success function will run 返回操作在成功功能运行之前运行

You may run sync request or redesign code to callbacks logic. 您可以运行同步请求或重新设计代码以回调逻辑。

For sync request your code will be: 对于同步请求,您的代码将是:

var designer_exists =  false;
function checkDesignerName(name)
{   
    designer_exists =  false;
    var designer_name = $('input[name="name"]').val();
    $.ajax( { async:false,
             type: "GET", 
             url: "/api/check_brand_exists/", 
             data : {name : designer_name }, 
             success: function(data) {
                    designer_exists = $.parseJSON(data);
                }}).statusText;
    return designer_exists;
}

As Dimitrov correctly noted it's asynchronous. 正如Dimitrov正确指出的那样,它是异步的。 If you want to encapsulate the ajax call within the function you could pass in the success callback. 如果要将ajax调用封装在函数中,则可以传递成功回调。

function checkDesignerName(name, successCallback)

and then you assign it to the jQuery ajax success function. 然后将其分配给jQuery ajax成功函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM