无法将json从php转换为html(有时可以工作,有时不会......)

时间:2016-04-19 18:18:22

标签: javascript php jquery html json

我需要一些帮助...

我有2个文件:

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

我的问题:

我抓住了提交事件并向register.php发了一个帖子请求。 寄存器文件工作正常,并将用户注册到数据库。问题是让json与register.php中的所有寄存器用户一起使用到form.html。 您可以看到我试图在回调函数中通过alert(json)提醒json,以检查它是否正常。 但是当我运行代码时,我很惊讶地看到行alert(json)有时会起作用,而且有时没有理性的原因...... 我只想清楚:行alert("inserting")和DB的实际用户注册工作正常。问题出在回调函数中......也许问题与寄存器文件的结尾有关(创建了json)。

感谢提前!

form.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">

register.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();
?>

2 个答案:

答案 0 :(得分:1)

对于服务器端,请尝试:

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;},然后在表单下方填写。

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

答案 1 :(得分:0)

我建议您使用promise接口,如下所示:

var jqXHR = $.post(url, data);
jqXHR.done(function(){
    console.log(jqXHR.responseText); //check php notices...
    console.info(jqXHR.responseJSON); //all ok
})
.fail(function(){
    console.error(jqXHR.responseText); // here you will likely find your problem
});

很可能你的php端有一些警告或错误,它会显示在fail回调上。另外,请检查chrome上的“网络”标签,了解除2XX以外的http状态。