简体   繁体   English

在文本框的onBlur事件上执行JavaScript函数

[英]JavaScript function execution on onBlur event of textbox

I wrote following : 我写了以下内容:

function loginName(txtLogin){
    var l = document.getElementById('txtLogin').value;
    <?php
        $query = sprintf("Select * from register where LoginName='%s'",
                        mysql_real_escape_string(l));

        //$query =  "Select * from register where UserName=$Username and     Pwd=$Password";
        $result = mysql_query($query);
        if($result)
        {
            $num_rows =  mysql_num_rows($result);
        }
    ?>
    if($num_rows < 1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

and call that function on onBlur event as below: 并在onBlur事件上调用该函数,如下所示:

 $('#txtLogin').blur(function() {
      if(loginName('txtLogin'))
      {
          //alert('Email is valid');
      }
      else
      {
          alert('Type another login name.');
      }
   });

But its not showing error when I enter same login name as exist in database.please help. 但是当我输入与数据库中相同的登录名时,它没有显示错误。请帮助。

you can not execute PHP inside <script> tags because it's only executing in client side, and PHP is a server side language. 您不能在<script>标记内执行PHP,因为它仅在客户端执行,并且PHP是服务器端语言。 Instead of this, you need to use AJAX to check the validity of the username. 取而代之的是,您需要使用AJAX来检查用户名的有效性。 BTW, you directly copy&paste'd your code from somewhere because return is not a valid keyword outside of a method. 顺便说一句,您直接从某处复制并粘贴代码,因为return不是方法外的有效关键字。 if you are familiar with jQuery (a javascript library), I recommend using it for the AJAX part. 如果您熟悉jQuery (JavaScript库),建议将其用于AJAX部分。

PHP code is run at the time page gets parsed. 在解析页面时运行PHP代码。 If you're expecting it to run when the JS function is executed then you will need to write your PHP code in an external file and call that by AJAX. 如果您期望它在执行JS函数时运行,那么您将需要在外部文件中编写PHP代码并通过AJAX调用它。

PHP runs on the server and outputs some text. PHP在服务器上运行,并输出一些文本。

That text is then interpreted as HTML and JavaScript by the browser. 然后,浏览器将该文本解释为HTML和JavaScript。

When you call a JavaScript functions, then any PHP inside it will already have run. 当您调用JavaScript函数时,其中的任何PHP都将已经运行。 You can't pass a variable from JavaScript to PHP like that. 您不能像这样将变量从JavaScript传递到PHP。

You must make a new HTTP request (eg by submitting a form, or using Ajax). 您必须发出新的HTTP请求(例如,提交表单或使用Ajax)。

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

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