javascript - Ajax/Jquery 问题将数据推送到后端

标签 javascript php jquery html ajax

首先,除了我的函数中的问题,我不确定我的代码中是否遗漏了任何东西,但我离题了。我是 jquery 的新手,所以我在设置注册页面时遇到了困难。在表单中,我试图检查有效条目以及使用 php 检查后端中的查询。我设置了 2 个文件,一个是 html 文件,另一个是 php 文件。使用 ajax 函数应该调用 php 文件,但我似乎无法让它工作,我想知道是否应该将所有代码放在同一个文件中。此外,我不确定这些功能是否能正常工作,因为它没有返回任何状态。我将在下面发布两个文件的代码。任何提示或技巧将不胜感激。

没有CSS的HTML文件

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8">
    <title>Register</title>

    <link rel="stylesheet" href="assets/css/reset.css">
    <link rel="stylesheet" href="assets/css/style.css">    

  </head>

  <body>
<script src="assets/js/jquery.min.js"> </script>
<script src="assets/js/main.js"> </script>


<div class="pen-title">
  <h1>Registration Form</h1></div>

  <script>
  function emptyElement(x){
    _(x).innerHTML = "";
}
  function signup(){
    var u = _("username").value;
    var e = _("email").value;
    var p1 = _("pass").value;
    var p2 = _("pass2").value;
    var status = _("status");
    if(u == "" || e == "" || p1 == "" || p2 == ""){
        status.innerHTML = "Fill out all of the form data";
    } else if(p1 != p2){
        status.innerHTML = "Your password fields do not match";
        } else 
        {
        _("submit").style.display = "none";
        status.innerHTML = 'please wait ...';
        var ajax = ajaxObj("POST", "registration.php");
        ajax.onreadystatechange = function() {
            if(ajaxReturn(ajax) == true) {
                if(ajax.responseText != "signup_success"){
                    status.innerHTML = ajax.responseText;
                    _("submit").style.display = "block";
                } else {
                    window.scrollTo(0,0);
                    _("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
                }
            }
        }
        ajax.send("u="+u+"&e="+e+"&p="+p1);
    }
}
</script>



<!-- Form Module-->
<div class="module form-module">
    <div class="form">
         </div>
  <div class="form">
    <h2>Create an account</h2>
    <form method="post" name="signupform" id="signupform" onsubmit="return false;">
      <input type="text" id="username" onfocus="emptyElement('status')" placeholder="Username" maxlength="50"/>
      <input type="password" id="pass" onfocus="emptyElement('status')"  placeholder="Password" maxlength="10"/>
      <input type="password" id="pass2" onfocus="emptyElement('status')" placeholder="Confirm Password" maxlength="10"/>
      <input type="email" id="email" onfocus="emptyElement('status')" placeholder="Email Address" maxlength="50"/>
      <!-- <input type="tel" name="telephone" placeholder="Phone Number" maxlength="10"/> -->
      <button type="submit" onclick="signup()" name="submit">Register</button>
    </form>
  </div>
</div>


  </body>
</html>

PHP文件

<?php  
// Connects to your Database 

$host="myhost"; // Host name 
$username="myuser"; // Mysql username 
$password="mypass"; // Mysql password 
$db_name="mydbname"; // Database name 

$con = mysqli_connect("$host", "$username", "$password", "$db_name") or die(mysql_error());

// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
    // GATHER THE POSTED DATA INTO LOCAL VARIABLES
    $u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
    $e = mysqli_real_escape_string($con, $_POST['e']);
    $p = $_POST['p'];
    // GET USER IP ADDRESS
    $ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
    // DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
    $sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
    $query = mysqli_query($con, $sql); 
    $u_check = mysqli_num_rows($query);
    // -------------------------------------------
    $sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
    $query = mysqli_query($con, $sql); 
    $e_check = mysqli_num_rows($query);
    // FORM DATA ERROR HANDLING
    if($u == "" || $e == "" || $p == ""){
        echo "The form submission is missing values.";
        exit();
    } else if ($u_check > 0){ 
        echo "The username you entered is alreay taken";
        exit();
    } else if ($e_check > 0){ 
        echo "That email address is already in use in the system";
        exit();
    } else if (strlen($u) < 3 || strlen($u) > 16) {
        echo "Username must be between 3 and 16 characters";
        exit(); 
    } else if (is_numeric($u[0])) {
        echo 'Username cannot begin with a number';
        exit();
    } else {
    // END FORM DATA ERROR HANDLING
        // Begin Insertion of data into the database
        // Hash the password and apply your own mysterious unique salt
        //$cryptpass = crypt($p);
        //include_once ("php_includes/randStrGen.php");
        //$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
        // Add user info into the database table for the main site table
        $sql = "INSERT INTO users (username, email, password, ip, signup, lastlogin, notescheck)       
                VALUES('$u','$e','$p' ,'$ip',now(),now(),now())";
        $query = mysqli_query($con, $sql); 
        $uid = mysqli_insert_id($con);
        // Establish their row in the useroptions table
        $sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
        $query = mysqli_query($db_conx, $sql);
        // Create directory(folder) to hold each user's files(pics, MP3s, etc.)
        //if (!file_exists("user/$u")) {
        //  mkdir("user/$u", 0755);
        //}
        }
        }
?>

最佳答案

您的 javascript 代码有很多错误。就像您使用 _ 而不是 $ 并且您的元素 ID 是错误的。它们不包括#。所以我用你的逻辑组织了你的代码。但这不是真正的问题,也不是真正的学习方法。 HTML

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8">
    <title>Register</title>

    <link rel="stylesheet" href="assets/css/reset.css">
    <link rel="stylesheet" href="assets/css/style.css">    

  </head>

  <body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!--script src="assets/js/main.js"> </script-->


<div class="pen-title">
  <h1>Registration Form</h1></div>

  <script>
  function emptyElement(x){
    $('#' + x).text("");
}
  function signup(){
    var un = $("#username").val();
    var em = $("#email").val();
    var p1 = $("#pass").val();
    var p2 = $("#pass2").val();
    if(un == "" || em == "" || p1 == "" || p2 == "")
    {
        $('#status').text("Fill out all of the form data");
    } 
    else if(p1 != p2)
    {
        $('#status').text("Your password fields do not match");
    } 
    else 
    {

        $.ajax({
            type: "POST",
            url: "registration.php",
            dataType: "json",
            data : { u: un, p:p1, e:em },
            cache: !1,
            beforeSend: function(){
                $("#submit").hide();
                $('#status').text('please wait ...');
            },
            complete: function(){
                $("#submit").show();
            },
            success: function(answer){
                if(answer.result == "successful")
                {
                    $("#status").html(answer.text);
                }
                else
                {
                    $("#status").html(answer.result);
                }
            },
            error: function(answer){
                $("#status").text(answer);
            }
        });
    }

        /*
        var ajax = ajaxObj("POST", "registration.php");
        ajax.onreadystatechange = function() {
            if(ajaxReturn(ajax) == true) {
                if(ajax.responseText != "signup_success"){
                    status.innerHTML = ajax.responseText;
                    $("submit").style.display = "block";
                } else {
                    window.scrollTo(0,0);
                    $("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
                }
            }
        }
        ajax.send("u="+u+"&e="+e+"&p="+p1);
        */
    }
</script>



<!-- Form Module-->
<div class="module form-module">
    <div class="form">
         </div>
  <div class="form">
    <h2>Create an account</h2>
    <form method="post" name="signupform" id="signupform" onsubmit="return false;">
      <input type="text" id="username" onfocus="emptyElement('status')" placeholder="Username" maxlength="50"/>
      <input type="password" id="pass" onfocus="emptyElement('status')"  placeholder="Password" maxlength="10"/>
      <input type="password" id="pass2" onfocus="emptyElement('status')" placeholder="Confirm Password" maxlength="10"/>
      <input type="email" id="email" onfocus="emptyElement('status')" placeholder="Email Address" maxlength="50"/>
      <!-- <input type="tel" name="telephone" placeholder="Phone Number" maxlength="10"/> -->
      <button type="submit" onclick="signup()" name="submit">Register</button>
      <div id="status"></div>
    </form>
  </div>
</div>


  </body>
</html>

注册.php

<?php
    $answer = new stdClass;
    if(isset($_POST))
    {
        $answer->result = "successful";
        $answer->text = "";
        foreach($_POST as $key => $value)
        {
            $answer->text .= $key . ": " . $value . "<br />";
        }
    }
    else
    {
        $answer->result = "Error";
        $answer->text = "Error Message";
    }
    echo json_encode($answer);
?>

这个 registration.php 是一个例子。你可以用你的逻辑重写。 您应该使用 $answer 对象进行响应。
$answer->result 是响应状态 $answer->text 是响应 我希望它能帮助你。

关于javascript - Ajax/Jquery 问题将数据推送到后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39795967/

相关文章:

javascript - 添加/删除 eventListeners,同时保持 "this"的实例上下文

javascript - 是否可以只将 dart 函数转换为 javascript

javascript - JS : Cross Browser Compatibility - my JS works in chrome, 不在 FF 中

jquery - 让 div 重叠多个表格单元格的最佳方法是什么

javascript - 如何在 AJAX 请求期间禁用 anchor 标记并更改 html()

php - 使用 PHP 和 JS 构建 AJAX 网络应用程序的良好 RPC 模型是什么?

javascript - 单击链接时如何使跨度更改颜色

php - 单击按钮打开多日期选择器

php - 从下拉列表中删除重复项

php - MySQL 根据另一个查询的结果更新表