在jQuery Ajax中返回true

杰罗姆

我在jquery中使用ajax来检查该值是否存在于数据库中。我们可以为此使用普通的select查询(php),但是如果值存在,我必须发出警报弹出窗口。这就是为什么我这样决定。我几乎完成了,但是问题是由于jquery中返回false而导致的,即使数据库中不存在名称,它也不允许下一行。我如何在那个特定的地方给真实的回报?

$.ajax({
    type:"post",
    url:"actionn.php",
    data:"name="+name,
    success:function(data){
        alert(data);        
        //if data does not exist means it should get out of ajax function            
    }
});
return false; //if data exists

if(name=="") //data does not exist means it should come here
{
    alert("Please enter your Name");
    return false;
}
努阿拉

正如t.niese指出的return true(或错误的),内部success并没有按照您预期的那样做。(另请参阅您的问题下的第一条评论)。

如果您的用户(不存在)内部,则实现目标的最直接的方法可能是使用您拥有的任何代码success

因此,基本上可以移动逻辑/代码,以使用户在success回调中存在/不存在时该怎么做
要获得更多见解,您确实应该阅读评论中提供的一些链接。

编辑:
我想你想念异步请求的概念-给定代码中的注释

$.ajax({
    type:"post",
    url:"actionn.php",
    data:"name="+name,
    success:function(data){
        alert(data);        
        //if data does not exist means it should get out of ajax function
        //ajax function has already "exited" here is the success callback
        //this code is executed when the request to action.php was succesfull
        //as in response code is 200/OK

    }
});
//return false; //if data exists
//nope, you don't know if data exists this code will be
//executed _while_ (!) a request to action.php is made!
//there is no guarantee when this request returns and you can't write code
//here which relies on the response

//if(name=="") //data does not exist means it should come here
//{
//    alert("Please enter your Name");
//    return false;
//}

您实际想要写的是这样的:

$.ajax({
    type:"post",
    url:"actionn.php",
    data:"name="+name,
    success:function(data){
        if(name==""){
            alert("Please enter your Name");
        }else{
            alert("Your name is: "+data);
        }
    }
});

酥脆而短。所有取决于服务器响应的逻辑都 successcallack中处理。之后 没有任何代码$.ajax依赖于data

请不要return参与$.ajax.success-这不是您认为的那样

对于进一步的问题,我想再次邀请您阅读有关Ajax调用的信息:https : //stackoverflow.com/a/14220323/1063730我认为有关重组代码的段落对您来说非常有趣。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章