如何声明 javascript 变量并将值分配给返回布尔值的 php 文件

发布于 2024-12-05 18:10:20 字数 3621 浏览 0 评论 0原文

对于上下文: 我正忙于使用 javascript 来检查表单中的字段。问题是解决无法从数据库检索数据的问题。除了确保其唯一(未在数据库中使用)用户名外,所有检查均已完成。我在网上查了很长一段时间,但唯一接近的答案是:“直到你开始需要相关的 php 页面返回某种类型的值。在这种情况下,只需使用 YUI 连接管理器或其他东西具有这种性质”。由于 php 是服务器端,因此当单击按钮时,可以调用 php,因为在用户名字段中有文本之前处理 php 是没有意义的。

这是我所做的。当按下提交按钮时,会调用 js 函数。检查有效。

<script type="text/javascript" src="regform_checks.js"></script>    

<h1>Welcome to Registration</h1>


<form name="register" action="add_user.php" onsubmit="return validateForm()" method="post">

<table>

<tr>

    <td>Choose a username*</td>

    <td><input type = "text" name="profile_id"/></td>

</tr>

上面是我的registration.php 下面是我的 .js 文件:

function validateForm()

 {

 var username=document.forms["register"]["profile_id"].value;

 var pw1=document.forms["register"]["profile_password"].value;

 var pw2=document.forms["register"]["profile_password2"].value;

 var invalid = " "; // Invalid character is a space

 var minLength2 = 3; // Minimum username length

 var minLength = 6; // Minimum password length

 var x=document.forms["register"]["profile_email"].value;

 var atpos=x.indexOf("@");

 var dotpos=x.lastIndexOf(".");


 //check for a value in username field

 if (username==null || username=="")

   {

   alert("Please enter a username");

   return false;

     }



 // check for username minimum length

 if (document.register.profile_id.value.length < minLength2) 

  {

  alert('Your username must be at least ' + minLength2 + ' characters long.');

  return false;

  }



 // check for a value in both fields.

 if (pw1 == "" || pw2 == "") 

  {

  alert("Please enter your password in the Password and Re-enter password areas.");

  return false;

  }



 // check for password minimum length

 if (document.register.profile_password.value.length < minLength) 

  {

  alert('Your password must be at least ' + minLength + ' characters long. Try again.');

  return false;

  }



 // check for password consistency

    if (pw1 != pw2) 

  {

  alert ("The passwords you have entered are not the same. Please re-enter your password.");

  return false;

  }



 //check for valid email address

 if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)

   {

   alert("Not a valid e-mail address");

   return false;

     }



 // check for spaces

 if (document.register.profile_id.value.indexOf(invalid) > -1) 

  {

  alert("Sorry, spaces are not allowed in your username.");

  return false;

  }

 else if (document.register.profile_password.value.indexOf(invalid) > -1)

  {

  alert("Sorry, spaces are not allowed in your password.");

  return false;

  }

 else if (document.register.profile_email.value.indexOf(invalid) > -1)

  {

  alert("Sorry, spaces are not allowed in your email.");

  return false;

      }

 else 

  {

   return true;

  }    



}

我无法做到的:设置一个 js 变量,如下所示: var username_check=profile_id_check.php; 该文件如下所示:

$query = "select profile_id from profile";

$result = mssql_query($query);

$names = array();

for ($count=0; $row=@mssql_fetch_array($result); $count++)

    $names[$count]=$row;


$idtest= True;

foreach ($names as $name)

{

if($name[profile_id]==$profile_id)

return false;
print "$name[profile_id]";

}

?>

php 代码仍在制作中,具体取决于需要做什么 我意识到我不需要 $idtest,因为 if 语句返回一个布尔值。最后一个打印语句仅打印所有配置文件名称(因此我可以确定代码有效,而且确实有效)。输入到表单中的配置文件名称需要与数据库中的所有配置文件名称进行比较,以确保其唯一。 我看到的最终结果是:如果用户名是唯一的,则不会给出错误或警告,如果不是,则 js 必须......我知道如何编码。 我愿意接受放弃这种方法的建议,尽管我的知识仅限于 php 和一些 js。 (显然是html) 提前致谢。

For context:
I am busy using javascript for checking fields in a form. The problem is to work around being unable to retrieve data from the database. All the checks except for making sure its a unique(not used in db) username are done. I looked around quite a while on the web, but the only answer that came close was this: "until you start needing the php page in question to return a value of some sort. in that case, just use the YUI connection manager or something of that nature". Since php is server side, when the button is clicked, can the php then be called, as there is no point in processing the php until there is text in the username field.

Here is what I have done. When pressing the submit button, a js function is called. The checking works.

<script type="text/javascript" src="regform_checks.js"></script>    

<h1>Welcome to Registration</h1>


<form name="register" action="add_user.php" onsubmit="return validateForm()" method="post">

<table>

<tr>

    <td>Choose a username*</td>

    <td><input type = "text" name="profile_id"/></td>

</tr>

This above is in my registration.php
The below is my .js file:

function validateForm()

 {

 var username=document.forms["register"]["profile_id"].value;

 var pw1=document.forms["register"]["profile_password"].value;

 var pw2=document.forms["register"]["profile_password2"].value;

 var invalid = " "; // Invalid character is a space

 var minLength2 = 3; // Minimum username length

 var minLength = 6; // Minimum password length

 var x=document.forms["register"]["profile_email"].value;

 var atpos=x.indexOf("@");

 var dotpos=x.lastIndexOf(".");


 //check for a value in username field

 if (username==null || username=="")

   {

   alert("Please enter a username");

   return false;

     }



 // check for username minimum length

 if (document.register.profile_id.value.length < minLength2) 

  {

  alert('Your username must be at least ' + minLength2 + ' characters long.');

  return false;

  }



 // check for a value in both fields.

 if (pw1 == "" || pw2 == "") 

  {

  alert("Please enter your password in the Password and Re-enter password areas.");

  return false;

  }



 // check for password minimum length

 if (document.register.profile_password.value.length < minLength) 

  {

  alert('Your password must be at least ' + minLength + ' characters long. Try again.');

  return false;

  }



 // check for password consistency

    if (pw1 != pw2) 

  {

  alert ("The passwords you have entered are not the same. Please re-enter your password.");

  return false;

  }



 //check for valid email address

 if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)

   {

   alert("Not a valid e-mail address");

   return false;

     }



 // check for spaces

 if (document.register.profile_id.value.indexOf(invalid) > -1) 

  {

  alert("Sorry, spaces are not allowed in your username.");

  return false;

  }

 else if (document.register.profile_password.value.indexOf(invalid) > -1)

  {

  alert("Sorry, spaces are not allowed in your password.");

  return false;

  }

 else if (document.register.profile_email.value.indexOf(invalid) > -1)

  {

  alert("Sorry, spaces are not allowed in your email.");

  return false;

      }

 else 

  {

   return true;

  }    



}

What I have been unable to do: set a js variable as follows:
var username_check=profile_id_check.php;
This file looks like this:

$query = "select profile_id from profile";

$result = mssql_query($query);

$names = array();

for ($count=0; $row=@mssql_fetch_array($result); $count++)

    $names[$count]=$row;


$idtest= True;

foreach ($names as $name)

{

if($name[profile_id]==$profile_id)

return false;
print "$name[profile_id]";

}

?>

The php code is still in progress of making, depending on what it needs done
I realize I dont need the $idtest, as the if statement returns a boolean value. That last print statement just prints all the profile names(so I can be sure the code works, and it does). And its the profile name entered into the form that needs to be compared with all the profile names in the database to ensure it is unique.
The endresult the way I see it: If username is unique, give no error or warning, if it isnt, the js must then... which I know how to code.
Im open to suggestions that turns away from this method, though my knowledge is restricted to php, some js. (and obviously html)
Thanks in advance.

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

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

发布评论

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

评论(3

野稚 2024-12-12 18:10:20

我认为您需要掌握有关如何在客户端和服务器之间来回传递数据的某些概念。您无法通过执行 var username_check=profile_id_check.php; 在客户端调用 php 文件。

数据可以通过请求方法传递到服务器。其中最常见的是 $_POST$_GET。查看下面表单标记上的属性。

<form name="register" action="add_user.php" onsubmit="return validateForm()" method="post">

操作设置为 add_user.php,方法设置为 post。因此,您可以使用 $_POST 数组在服务器端访问带有 name 属性的表单元素。因此,作为 add_user.php 中的示例,您可以通过以下方式访问 profile_id 。

$profile_id = $_POST['profile_id']; 

您可以将数据发送回服务器的其他方法是通过 ajax 但我建议了解通过常规 HTTP 请求提交数据的基础知识,然后再转向 ajax。

I think you need to get a grasp of certain concepts on how to pass data back and forth between the client and server. You cannot call a php file on the client side by doing var username_check=profile_id_check.php;.

Data can be passed to the server via request methods. The most common of which are $_POST and $_GET. Have a look at the attributes on your form tag below

<form name="register" action="add_user.php" onsubmit="return validateForm()" method="post">

The action is set to add_user.php and your method is set to post. So, you can access the form elements with a name attribute on the server side using the $_POST array. So as an example in your add_user.php you can access the profile_id in the following way.

$profile_id = $_POST['profile_id']; 

Other ways you can send data back to the server is by ajax but i would suggest getting the basics down of submitting data via regular HTTP requests then move onto ajax later on.

月朦胧 2024-12-12 18:10:20

您应该向特定的 php 文件发出 ajax 请求,并注册一个处理 php 输出并设置变量的回调函数。
所以类似的东西

/* code block #1 */
var username_check=profile_id_check.php;
/* code block #2 */

会被翻译成类似的东西:

/* code block #1 */
var username_check;
ajaxCall({
    url : 'profile_id_check.php',
    callback : function(response){
        username_check = response;
        /* code block #2 */
    }
});

You should make an ajax request to the specific php file and register a callback function that handles the php output and sets your variable.
So something like

/* code block #1 */
var username_check=profile_id_check.php;
/* code block #2 */

would be translated into something like :

/* code block #1 */
var username_check;
ajaxCall({
    url : 'profile_id_check.php',
    callback : function(response){
        username_check = response;
        /* code block #2 */
    }
});
浮光之海 2024-12-12 18:10:20

我不是 100% 确定你在问什么,因为似乎存在一些语言障碍问题,但看起来你是在问如何让 JavaScript 与 PHP 交互。

PHP 是服务器端的。更重要的是,PHP 不会作为服务器上的进程(通常......)运行,因此当您运行脚本时,这是一次性的。这最终意味着当 PHP 脚本将输出呈现到屏幕上时,脚本本身已经完成运行。它不像控制台程序那样坐在那里等待输入。

因此,您需要使用 AJAX 才能访问 PHP 脚本。什么是 AJAX?简而言之,它是 JavaScript 向服务器端脚本发送 HTTP 请求、接收这些请求的结果,然后动态使用 DOM(文档对象模型 - 您的 HTML)显示这些结果的一种方式。

使用 AJAX 最简单的方法是使用 jQuery 极其优雅的 AJAX 函数:

http://api.jquery.com /jQuery.get/

http://api.jquery.com/jQuery.post/< /a>

最后一个想法:使用 JavaScript 进行表单验证是不是安全措施。确保您的 PHP 脚本中也有验证。

I'm not 100% sure what you're asking, as there seems to be a bit of a language barrier issue, but it looks like you're asking how to have your JavaScript interact with your PHP.

PHP is server-side. What's more is that PHP doesn't run as a process (usually...) on the server, so when you run a script, it's a one-shot deal. This ultimately means that by the time your PHP script renders output to the screen, the script itself has finished running. It is not sitting there awaiting input like, say, a console program.

Because of this, you need to use AJAX in order to access your PHP script. What is AJAX? Simply put, it's a way for JavaScript to send HTTP requests to a server-side script, receive the results of those requests, and then dynamically use the DOM (Document Object Model - your HTML) to display those results.

The simplest way to use AJAX is to use jQuery's ridiculously elegant AJAX functions:

http://api.jquery.com/jQuery.get/

http://api.jquery.com/jQuery.post/

One final thought: Form validation with JavaScript is not a security measure. Make sure you have validation in your PHP script as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文