简体   繁体   English

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

[英]How declare a javascript variable and assign the value to a php file which returns a boolean value

For context: I am busy using javascript for checking fields in a form. 对于上下文:我正忙于使用javascript检查表单中的字段。 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. 除确保其唯一(未在db中使用)用户名外,所有检查均已完成。 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". 我在网上浏览了好一阵子,但是唯一接近的答案是:“直到您开始需要相关的php页面来返回某种值。在这种情况下,只需使用YUI连接管理器或其他工具即可。这种性质”。 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. 由于php是服务器端,因此单击按钮时可以调用php,因为在用户名字段中没有文本之前,没有必要处理php。

Here is what I have done. 这是我所做的。 When pressing the submit button, a js function is called. 当按下提交按钮时,将调用一个js函数。 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: 上面是我的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;

  }    



}

What I have been unable to do: set a js variable as follows: var username_check=profile_id_check.php; 我一直无法做的事情:如下设置js变量: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. php代码仍在制作中,具体取决于它需要完成的工作,我意识到我不需要$ idtest,因为if语句返回一个布尔值。 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. 我看到的结果是:如果用户名是唯一的,则不给出错误或警告,如果不是,则js必须...我知道如何编码。 Im open to suggestions that turns away from this method, though my knowledge is restricted to php, some js. 我乐意接受一些偏离此方法的建议,尽管我的知识仅限于php和一些js。 (and obviously html) Thanks in advance. (显然是html)在此先感谢。

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; 您无法通过执行var username_check=profile_id_check.php;来在客户端调用php文件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 . 其中最常见的是$_POST$_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. 该操作设置为add_user.php,您的方法设置为post。 So, you can access the form elements with a name attribute on the server side using the $_POST array. 因此,您可以使用$_POST数组在服务器端使用name属性访问表单元素。 So as an example in your add_user.php you can access the profile_id in the following way. 因此,以add_user.php中的示例为例,您可以通过以下方式访问profile_id。

$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. 您可以通过ajax将数据发送回服务器的其他方式,但我建议您通过常规HTTP请求提交数据的基础知识,然后再转到ajax。

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. 您应该向特定的php文件发出ajax请求,并注册一个处理php输出并设置变量的回调函数。
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 */
    }
});

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. 我似乎不确定您在问什么,因为似乎存在一些语言障碍问题,但是您似乎在问如何让JavaScript与PHP交互?

PHP is server-side. PHP是服务器端的。 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. 更重要的是,PHP不在服务器上作为进程运行(通常是...),因此,当您运行脚本时,这是一次性的交易。 This ultimately means that by the time your PHP script renders output to the screen, the script itself has finished running. 最终,这意味着当您的PHP脚本将输出呈现到屏幕时,脚本本身已经完成运行。 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. 因此,您需要使用AJAX来访问您的PHP脚本。 What is AJAX? 什么是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. 简而言之,这是JavaScript将HTTP请求发送到服务器端脚本,接收这些请求的结果,然后动态使用DOM(文档对象模型-HTML)显示这些结果的一种方式。

The simplest way to use AJAX is to use jQuery's ridiculously elegant AJAX functions: 使用AJAX的最简单方法是使用jQuery可笑的优雅AJAX函数:

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

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

One final thought: Form validation with JavaScript is not a security measure. 最后一个想法:使用JavaScript进行表单验证不是一种安全措施。 Make sure you have validation in your PHP script as well. 确保您的PHP脚本中也有验证。

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

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