javascript 一起使用javascript和php来验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10326362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:29:08  来源:igfitidea点击:

using javascript and php together to validate

phpjavascript

提问by droidus

How do I use php and javascript together? from doing my own research, it seems impossible. I understand that they are different, and they each have their own special things that they do. But let's say you are validating a form. You use javascript to validate the form, then if there are no errors, you run php to insert a record. How would you do this? Is there any way to run php in javascript or call on a php method?

如何同时使用 php 和 javascript?从我自己的研究来看,这似乎是不可能的。我知道他们是不同的,他们每个人都有自己的特别之处。但是假设您正在验证表单。您使用 javascript 来验证表单,然后如果没有错误,则运行 php 以插入一条记录。你会怎么做?有没有办法在javascript中运行php或调用php方法?

回答by jeremysawesome

Generally you will see Javascript used as client sidecode. This means that a browser that visits your website will download your Javascript code, compile it, and run it itself. Client side code simply means that the client (person who visits your website) runs the code.

通常,您会看到 Javascript 用作客户端代码。这意味着访问您网站的浏览器将下载您的 Javascript 代码、编译它并自行运行。客户端代码只是意味着客户端(访问您网站的人)运行代码。

PHP, on the other hand, is used as server sidecode. This means that your web server parses and runs your code. Server side code simply means that the code is run on your web server.

另一方面,PHP 用作服务器端代码。这意味着您的 Web 服务器会解析并运行您的代码。服务器端代码仅意味着代码在您的 Web 服务器上运行。

You can give information to Javascript from PHP code. For example:

您可以从 PHP 代码向 Javascript 提供信息。例如:

<?php
    $myVariable = 'a testing variable';
?>
<script type='text/javascript'>
    var fromTheServer = '<?php echo $myVariable; ?>';
</script>

The Javascript variable fromTheServeris set to the value of the php variable myVariable. All this is really doing is outputting the value of the php variable as a string, which Javascript uses. This approach can be useful, say if you wanted a Javascript array of shopping cart items the user currently has in their cart.

Javascript 变量fromTheServer被设置为 php 变量myVariable的值。所有这些真正做的是将 php 变量的值作为字符串输出,Javascript 使用它。这种方法很有用,例如,如果您想要用户当前在其购物车中拥有的购物车项目的 Javascript 数组。

<?php
    // get some shopping cart items using a function
    $shoppingCartItemsArray = getShoppingCartItems();
?>
<script type='text/javascript'>
    var shoppingCartItemsArray = "<?php echo implode('|', $shoppingCartItemsArray); ?>";

    // split the string value by the | delimeter to get an array
    shoppingCartItemsArray = shoppingCartItemsArray.split('|');
</script>

Now you have seen how you can integrate php with Javascript a little bit. Once again, this isn't really integrating, just outputting information from the server. What about sending information to the server? This is where AJAX comes in.

现在您已经看到了如何将 php 与 Javascript 集成一点点。再一次,这并不是真正的集成,只是从服务器输出信息。向服务器发送信息怎么样?这就是 AJAX 的用武之地。

Say you are implementing a drag and drop shopping cart with Javascript. The idea is that the user picks an item from your site and drags it to their shopping cart. Upon letting go of the item, the item should be added to the users cart on the server. You would be using AJAX to post the item number to the server and wait for the server to tell you whether the item was successfully added. Note: You can build your own AJAX methods making use of native Javascript code, however, why do that when you can use a framework that has it built in? I generally use jQuery, but there are a number of other JS frameworksout there you can use.

假设您正在使用 Javascript 实现拖放式购物车。这个想法是用户从您的网站选择一个项目并将其拖到他们的购物车中。放开物品后,该物品应添加到服务器上的用户购物车中。您将使用 AJAX 将商品编号发布到服务器并等待服务器告诉您商品是否已成功添加。注意:您可以使用原生 Javascript 代码构建自己的 AJAX 方法,但是,当您可以使用内置它的框架时,为什么要这样做呢?我通常使用jQuery,但您可以使用许多其他 JS 框架

The following very simple example shows how an interaction with Javascript and php could look like under the above circumstance. It uses jQuerys $.ajax();function.

以下非常简单的示例显示了在上述情况下与 Javascript 和 php 交互的样子。它使用jQuerys$.ajax();函数。

<?php
    /** File: https://www.example.com/cart.php **/
    // .. code
    if($_POST['action'] === 'addItem'){
        $result = addItemToCart($_POST['itemId']);
        echo $result;
    }
    // ... code

?>
<script type='text/javascript'>
    // code ....
        $.ajax({
            url: 'https://www.example.com/cart.php'
            type: 'POST',
            data: {
                action: 'addItem',
                itemId: getDraggedItem() // get the item id from a function
            }
            success: function(result){
                $('#ServerMessage').html(result);
            }
        });
    // code ....
</script>

Ok, so now you can very briefly see how php and Javascript are acting ifjavascript is being used as client side code.

好的,现在您可以非常简要地看到如果javascript 被用作客户端代码,php 和 Javascript 的行为。

Javascript can also be used as Server Side code, for example, IIS allows you to run JScript in tangent with VBScript.

Javascript 也可以用作服务器端代码,例如,IIS 允许您与 VBScript 相切地运行 JScript

<script type='text/javascript' runat='server'>
   Response.Write("MS Server here.")
</script>

In addition to this, CommonJSprovides an API for server-side Javascript code which many projects are now implementing. You may have heard of some of these, Node.jsin particular. One of these projects may allow you to run php and javascript in conjunction with eachother, you'll have to look.

除此之外,CommonJS为服务器端 Javascript 代码提供了一个 API,许多项目现在都在实现它。您可能听说过其中一些,尤其是Node.js。这些项目之一可能允许您同时运行 php 和 javascript,您必须查看。

The bottom line is, Javascript is not only client side code. It's simply code that can be executed on either the server or the client, or as a way to clean up your iTunes library.

最重要的是,Javascript 不仅仅是客户端代码。它只是可以在服务器或客户端上执行的简单代码,或者作为清理 iTunes 资料库的一种方式

回答by enbits

You need to validate in both JavaScript and PHP. But most important is PHP validation because remember: Javascript is frontend code, therefore can be modified or simply disabled by the user. So before inserting you must validate in PHP.

您需要在 JavaScript 和 PHP 中进行验证。但最重要的是 PHP 验证,因为请记住:Javascript 是前端代码,因此可以由用户修改或简单地禁用。因此,在插入之前,您必须在 PHP 中进行验证。

There are thousands of javascript validation plugins, a good one is jQuery Validate: http://bassistance.de/jquery-plugins/jquery-plugin-validation/

有数以千计的 javascript 验证插件,一个很好的就是 jQuery Validate:http: //bassistance.de/jquery-plugins/jquery-plugin-validation/

You have an example here on PHP validation: http://buildinternet.com/2008/12/how-to-validate-a-form-complete-with-error-messages-using-php-part-1/

你有一个关于 PHP 验证的例子:http: //buildinternet.com/2008/12/how-to-validate-a-form-complete-with-error-messages-using-php-part-1/

回答by itotallyrock

<?php
  if(PHP VALIDATION) {
    echo 'You were not validated';
  } else {
    echo "<script src=\"FILE WITH UR JAVASCRIPT\"><script>"
  }
?>

This javascript will only load and executed if the php validation is complete.

只有在 php 验证完成后,这个 javascript 才会加载和执行。

回答by ron

You can validate using javascript and insert records using php. But, it is much better if you will validate the records with javascript and php. Why? Because javascript validation will be useless when you turn off javascript in your browser, that means, if browser javascript is off, no validations will run and that means the invalid records will be inserted to your database. So it is much better to have a backup php validation.

您可以使用 javascript 进行验证并使用 php 插入记录。但是,如果您使用 javascript 和 php 验证记录会好得多。为什么?因为当您在浏览器中关闭 javascript 时,javascript 验证将无用,这意味着,如果浏览器 javascript 关闭,则不会运行任何验证,这意味着无效记录将被插入到您的数据库中。所以最好有一个备份的 php 验证。

回答by Khalid Okiely

lets have this simple example: the example given uses jquery, you might google that up. html:

让我们举一个简单的例子:给出的例子使用 jquery,你可以谷歌一下。html:

 <html>
      <body>
      <input type = "text" name = "username" id = "username"></input>
      <input type = "button" name = "submit" id = "save_button" value = "insert"></input>
        <div id = "save_stat"></div> <!--This will be the status of the insertion. "loading   or sucess!"---->
         <script>
        $('#save_button').click(function(){ //assign an event handler
           //grab values
           var name = $('#username').val(); //get the value of whatever the user entered
             //perform HTTP ajax request
             //could be $.get instead
             $.post('phpfile.php', (name:name)/*this could be modified to (name:name, password: password) etc.*/, function(data){ //send the data to the php file.
                 $('#save_stat').html(data);
              });
         });
      </script>
     </body>
    </html>

Now all that is left to do is create the php registration page and link it instead of the "phpfile.php" And to load values in that file, sinply use $_POST['name']; OR $_POST['password']; etc.

现在剩下要做的就是创建 php 注册页面并链接它而不是“phpfile.php”并且要在该文件中加载值,只需使用 $_POST['name']; 或 $_POST['密码']; 等等。

The above answers(suggested by others) are perfect, as they suggest the essence of what you actually require to create an in-sync Javascript and php application.

上面的答案(由其他人建议)是完美的,因为它们暗示了创建同步 Javascript 和 php 应用程序实际需要的本质。

***EDIT NOTICE********When creating the php, use echo statement when giving the user messages, i.e

** *EDIT NOTICE *** *****创建php时,给用户消息时使用echo语句,即

if(!empty($_POST['name'])){
echo "You successfully entered your name!"; 
}else
   echo "you forgot to enter a name";

Sample #2

样品#2

if(!empty($_POST['name'])){
$message = "You successfully entered your name!"; 
}else
   $message = "you forgot to enter a name";
    echo $message;