javascript - 无法从 php 获取 json 到 html(有时有效,有时无效..)

标签 javascript php jquery html json

我需要一些帮助...

我有 2 个文件:

  • 包含 html 表单的 form.html
  • register.php-从表单获取post请求,在数据库中注册用户并返回包含所有注册用户的json(我想在注册成功后立即在form.html中显示它们)。

我的问题:

我捕获了提交事件并向register.php发出了发布请求。 注册文件工作正常并将用户注册到数据库。问题是从register.php 到form.html 获取所有注册用户的json。 你可以看到我尝试通过 alert(json) 来提醒 json在回调函数中只是为了检查它是否正常。 但是当我运行代码时,我惊讶地发现 alert(json) 行有时有效,有时无效,没有合理的理由...... 我只是想澄清一下:行 alert("inserting")并且实际的用户注册到数据库工作正常。问题出在回调函数中...也许问题与寄存器文件的结尾(json 的创建)有关。

提前致谢!

表单.html

        $( "#myForm" ).submit(function( event ) {
                        if(!validateForm()) //there is error
                        {
                            event.preventDefault();
                        }
                        else
                        {
                            alert("inserting");

                            $(function(){
                                $('#myForm[name=new_post]').submit(function(){
                                  $.post($(this).attr('action'), $(this).serialize(), function(json) {
                                    alert(json);
                                  }, 'json');
                                  return false;
                                });
                            });
                        }
        });

表单定义:<form class="form-horizontal" id="myForm" role="form" method="POST" action="register.php">

注册.php

<?php
    $srevernme = "localhost";
    $username = "root";
    $password = "";
    $dbname = "mydb";
    //create connection
    $conn = new mysqli($srevernme,$username,$password,$dbname);

    //check connection
    if($conn->connect_error)
        die("connection failed:". $conn->connect_error);

    if ($_SERVER['REQUEST_METHOD'] == "POST") 
    {        
        if (isset($_POST["fnameInput"]) && isset($_POST["lnameInput"]) && isset($_POST["addressInput"]) && isset($_POST["cityInput"]) && isset($_POST["zipcodeInput"]))
        {
            //add new users
            // prepare and bind
            $stmt = $conn->prepare("INSERT INTO users (first_name, last_name, address, city, zipcode) VALUES (?, ?, ?, ?, ?)");
            if ($stmt == FALSE)
                die("Connection failed:");
            $stmt->bind_param("sssss",$firstname,$lastname,$address,$city,$zipcode);
            $firstname = $_POST["fnameInput"];
            $lastname = $_POST["lnameInput"];
            $address = $_POST["addressInput"];
            $city = $_POST["cityInput"];
            $zipcode = $_POST["zipcodeInput"];
            $stmt->execute();
            $stmt->close();


            //get all registers users

            $stmt2 = $conn->prepare("SELECT last_name,first_name FROM users ORDER BY last_name");
            if ($stmt2 == FALSE)
                die("Connection failed:");
            $stmt2->execute();                   
            $result = $stmt2->get_result();

            $arrayFormat = array();
            while($row = $result ->fetch_assoc())
            { 
                $arr = array('last_name'=>$row['last_name'],'first_name'=>$row['first_name']);
                $tmp_json = json_encode($arr);
                array_push($arrayFormat,$tmp_json);  
            }
            echo json_encode($arrayFormat, JSON_FORCE_OBJECT);

            $stmt2->close();
        }
    }

    $conn->close();
?>

最佳答案

对于服务器端,试试这个:

if($conn->connect_error):
    die("connection failed:". $conn->connect_error);
endif;
if ($_SERVER['REQUEST_METHOD'] == "POST"): 
   if (isset($_POST["fnameInput"]) && isset($_POST["lnameInput"]) 
       && isset($_POST["addressInput"]) && isset($_POST["cityInput"]) 
       && isset($_POST["zipcodeInput"])):
        $stmt = $conn->prepare("INSERT INTO `users` 
                (first_name, last_name, address, city, zipcode) 
                VALUES (?, ?, ?, ?, ?)");
        if ($stmt == FALSE):
            die("Connection failed:");
        endif;            
        $stmt->bind_param("sssss",$firstname,$lastname,$address,$city,$zipcode);
        $firstname = $_POST["fnameInput"];
        $lastname = $_POST["lnameInput"];
        $address = $_POST["addressInput"];
        $city = $_POST["cityInput"];
        $zipcode = $_POST["zipcodeInput"];
        $stmt->execute();
        $stmt->close();
        $stmt2 = $conn->prepare("SELECT last_name,first_name 
                                 FROM `users` ORDER BY last_name");
        if ($stmt2 == FALSE):
            die("Connection failed:");
        endif;
        $stmt2->execute();                   
        $result = $stmt2->get_result();
  $formatArray= array();
  while($row = $result->fetch_assoc()):
     array_push($formatArray, $row); //push result to $formatArray     
  endwhile;
  echo json_encode($formatArray, JSON_FORCE_OBJECT);
  $stmt2->close();
 endif;    
endif;
$conn->close();

对于客户端:

var form = $("#myForm");
$('#myForm[name=new_post]').submit(function(e){
  e.preventDefault();
 $.ajax({
        type:"POST",
        url:"register.php",
        data:form.serialize(),
        dataType:"json", 
        success: function(json){ 
        if(json){
            var len = json.length;//we calculate the length of the json
            var txt = "";//open a blank txt variable
            if(len > 0){ //if length is greater than zero
               for(var i=0;i<len;i++){ //as long as len is greater than i variable
                 if(json[i].first_name && json[i].last_name){
                 //we start storing the json data into txt variable
                     txt += "<tr><td>"+json[i].last_name+"</td>
                                  <td>"+json[i].first_name+"</td>
                             </tr>";
                   }
                }
            if(txt != ""){ 
            //If data is there we remove the hidden attribute
            //and append the txt which contains the data into the table
            //The table is given an id named 'table'.
               $("#table").append(txt).removeClass("hidden");
            }
         }
      }
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert('error: ' + textStatus + ': ' + errorThrown);
     }       
 });
});

在提交表单之前,您可能想隐藏表格,因此在 CSS 中添加 .hidden{display:none;},然后添加到 form.html 中的表单下方。

<table id="table" class="hidden">       
    <tr>
        <th>First name</th>
        <th>Last name</th>
    </tr>
</table>

关于javascript - 无法从 php 获取 json 到 html(有时有效,有时无效..),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36726406/

相关文章:

javascript - Chart.js 条形图不会从零开始作为最小值

javascript - 显示折线图 nvd3.js 中的所有标签?

javascript - jQuery 自动完成,输入触发另一个绑定(bind)

javascript - 如何使用 javascript 将突出显示的单词包含在带有一些标签的文本区域中?

javascript - 无法连续两次启动相同的动画

php - Sonata 管理 Controller + 依赖注入(inject)

javascript - 日期选择器 : Cannot set property 'currentDay' of undefined when multiple array id

php - MVC,CodeIgniter,在 View 中使用条件语句?

javascript - Input Type Range 控件在 IE 中显示为文本框

jquery - 寻找比 IF、ELSEIF、ELSE 方法更好的解决方案