【问题标题】:error Unexpected token < in json response错误意外的令牌<在json响应中
【发布时间】:2016-01-19 12:42:37
【问题描述】:

我试图通过 javaScript 文件将用户信息输入数据库,方法是将其链接到 .php 文件,它会抛出“意外令牌

.html

                             <form id="form" name = "form" method = "POST" action="form_banking1.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
                                <!--<h1>Please fill the below details</h1>-->
                                <fieldset>
                                    <!--<h2>Account Information</h2>-->
                                    <div class="row">

                                            <div class="col-sm-12 form-group">
                                                <input type="text" placeholder="Current address" class="form-control required" id="ca" name="ca" required="">
                                            </div>

                                            <div class="col-sm-4 form-group">
                                                <input type="text" placeholder="House no" class="form-control required" id="hno" name="hno" required="">
                                            </div>  
                                            <div class="col-sm-4 form-group">
                                                <input type="text" placeholder="Road no" class="form-control required" id="rno" name="rno" required="">
                                            </div>  
                                            <div class="col-sm-4 form-group">
                                                <input type="text" placeholder="Location" class="form-control required" id="location" name="location" required="">
                                            </div>

                                        <div class="col-sm-3 form-group">
                                            <select type="text" class="form-control required" name="country" required="">
                                            <option value="">Country</option>
                                            <option value="1">India</option>

                                            </select>
                                        </div>  
                                        <div class="col-sm-3 form-group">
                                        <select type="text" class="form-control required" id="state" name="state" required="">
                                            <option value="">State</option>
                                            <option value="1">Karnataka</option>

.                                            </select>
                                        </div>  
                                        <div class="col-sm-3 form-group">
                                            <select type="text" class="form-control required" id="city" name="city" required="">
                                            <option value="">City</option>
                                            <option value="1">Bengaluru</option>

                                            </select>
                                        </div>

                                        <div class="col-sm-3 form-group">
                                            <input type="text" placeholder="Pin no" class="form-control required"  id="pin" name="pin" required="">
                                        </div>

                                        <div class="col-sm-12 form-group">
                                            <select type="text" class="form-control required" id="doctitle" name="doctitle" required="">
                                            <option value="">Document Title</option>
                                            <option value="1">Aadhar Card</option>
                                            <option value="2">Pan Card</option>
                                            <option value="3">Ration Card</option>
                                            <option value="4">Green Card</option>
                                            <option value="5">Social Security Card</option>
                                            <option value="6">Voter ID</option>
                                            <option value="7">Driving License</option>
                                            <option value="8">Add New</option>
                                            </select>
                                        </div>

                                        <div class="col-sm-4 form-group">
                                                <input type="text" placeholder="Document no" class="form-control required"  id="docno" name="docno" required="">
                                        </div>  

                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Issued Authority" class="form-control required"  id="ia" name="ia" required="">
                                        </div>

                                        <div class="col-sm-4 form-group">
                                           <input type="text" placeholder="Date of Expiry" class="form-control required"  id="doe" name="doe" required="">
                                        </div>

                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Passport no" class="form-control required" id="pno" name="pno" required="">
                                        </div>  
                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Issued Authority" class="form-control required"  id="pissuedby" name="pissuedby" required="">
                                        </div>  
                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Date of Expiry" class="form-control required" id="pdoe" name="pdoe" required="">
                                        </div>
                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Visa no" class="form-control required" id="vno" name="vno" required="">
                                        </div>  
                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Issued Authority" class="form-control required"  id="vissuedby" name="vissuedby" required="">
                                        </div>  
                                        <div class="col-sm-4 form-group">
                                            <input type="text" placeholder="Date of Expiry" class="form-control required" id="vdoe" name="vdoe" required="">
                                        </div>
                                            <div class="col-sm-4 form-group">
                                            <input class="form-control " type="file" name = "doc" id = "doc" required="">
                                        </div>

                                            <div class="col-sm-4 form-group">
                                                <input style="width:100%" type="submit" name = "submit" id = "submit" value = "Save"  class="btn btn-success">
                                            </div><!--==== End col-sm-4 form-group==--> 

                                        </div>
                                        <div class="col-lg-4">
                                            <div class="text-center">
                                                <div style="margin-top: 20px">
                                                    <i class="" style="font-size: 180px;color: #e5e5e5 "></i>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                </fieldset>

                                </form>

    </body>

    </html>

.js

        $(document).ready(function(){
    $("#submit").click(function(e){
        e.preventDefault();

        var status = $('form')[0].checkValidity();
        if(status){
            var formData = new FormData($('form')[0]);

            $.ajax({
                url: "form_citizenship.php",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                dataType: "JSON",   

                success: function(json){
                    if(json.error){
                        alert(json.error_msg);
                    }else{
                        alert(json.docno);
                    }
                },

                error: function(jqXHR, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });
        }

    });
});

.php

       <?php
session_start();
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','miisky');

$response = array();

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

if(!mysqli_connect_errno()){

    $error_flag = false;
    /*foreach($_POST as $value){
        if(empty($value)){
            $error_flag = true;
            break;
        }
    }*/

    if(!$error_flag){

        //receiving post parameters
        $ca =$_POST['ca'];
        $hno = trim($_POST['hno']);
        $rno = trim($_POST['rno']);
        $location = trim($_POST['location']);
        $country = trim($_POST['country']);
        $state = trim($_POST['state']);
        $city = trim($_POST['city']);
        $pin = trim($_POST['pin']);
        $doctitle = trim($_POST['doctitle']);
        $docno = trim($_POST['docno']);
        $ia = trim($_POST['ia']);
        $doe = trim($_POST['doe']);
        $pno = trim($_POST['pno']);
        $pissuedby = trim($_POST['pissuedby']);
        $pdoe = trim($_POST['pdoe']);
        $vno = trim($_POST['vno']);
        $vissuedby = trim($_POST['vissuedby']);
        $vdoe = trim($_POST['vdoe']);

        if(isset($_FILES["doc"]["name"]) && !empty($_FILES["doc"]["name"])){

            //image insertion
            $target_dir = 'doc_uploads/';
            $target_file = $target_dir . basename($_FILES["doc"]["name"]);

            $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

            $check = getimagesize($_FILES["doc"]["tmp_name"]);
            if($check !== false){

                if (!file_exists($target_file)){

                    if($_FILES["doc"]["size"] <= 2097152){

                        $permissible_images = array('jpg', 'png', 'jpeg', 'gif');
                        if(in_array($imageFileType, $permissible_images)){

                            if (move_uploaded_file($_FILES["doc"]["tmp_name"], $target_file)){

                                // create a new user profile
                                $sql = "INSERT INTO citizen_info(ca, hno, rno, location, country, state, city, pin, doctitle, docno, ia, doe, pno, pissuedby, pdoe, vno, vissuedby, vdoe, doc, created_at) VALUES ('$ca', '$hno', '$rno', '$location', '$country', '$state', '$city', '$pin', '$doctitle', '$docno', '$ia', '$doe', '$pno', '$pissuedby', '$pdoe', '$vno', '$vissuedby', '$vdoe', '$target_file', NOW())";
                                if(mysqli_query($con,$sql)){
                                    $response["error"] = false;
                                    $response['docno'] = $docno;
                                    echo json_encode($response);

                                }else{
                                    $response["error"] = true;
                                    $response["error_msg"] = "INSERT operation failed";
                                    echo json_encode($response);
                                }
                            }else{
                                // Throw Error Here
                                $response["error"] = true;
                                $response["error_msg"] = "File could not be uploaded";
                                echo json_encode($response);
                            }

                        }else{
                            $response["error"] = true;
                            $response["error_msg"] = "Only jpg, png and gif images are allowed";
                            echo json_encode($response);
                        }

                    }else{
                        $response["error"] = true;
                        $response["error_msg"] = "file size is above 2MB";
                        echo json_encode($response);
                    }

                }else{
                    $response["error"] = true;
                    $response["error_msg"] = "file already exists";
                    echo json_encode($response);
                }

            }else{
                $response["error"] = true;
                $response["error_msg"] = "invalid image format";
                echo json_encode($response);
            }

        }else{
            $response["error"] = true;
            $response["error_msg"] = "Empty file";
            echo json_encode($response);
        }

    }else{
        $response["error"] = true;
        $response["error_msg"] = "Few fields are missing";
        echo json_encode($response);
    }

}else{
    $response["error"] = true;
    $response["error_msg"] = "Database connection failed";
    echo json_encode($response);
}
 ?>

【问题讨论】:

  • 使用同步调用是一种不好的做法。
  • 我敢打赌,你没有返回有效的 JSON,从你的 PHP 的外观来看,你不是。
  • 但是先生正在编码 $response..!!
  • 你到处都有回声。在控制台中查看服务器返回的内容。
  • 但是先生,当我直接以 html 中的 form_citizenship.php 形式进行操作时,它以 json 格式给出结果..!!

标签: javascript php json html


【解决方案1】:

我想指出几件事。

  • 您的表单验证var status = $('form')[0].checkValidity(); 将不起作用,因为您没有在&lt;input ...&gt; 元素中包含required 属性。像这样包含它们:

    <input type="text" placeholder="Current address" class="form-control required" id="ca" name="ca" required>
    
  • 首先使用e.preventDefault(); 防止您的表单被提交。
  • 如果您通过 AJAX 上传文件,请使用 FormData 对象。但请记住,旧浏览器不支持 FormData 对象。 FormData 支持从以下桌面浏览器版本开始:IE 10+、Firefox 4.0+、Chrome 7+、Safari 5+、Opera 12+。
  • 在您的 AJAX 请求中设置以下选项,processData: falsecontentType: false。请参考 the documentation 了解这些功能。
  • 最后,在form_citizenship.php 页面上正确验证您的表单输入,因为现在它完全是一团糟。

所以你的 jQuery 应该是这样的:

$(document).ready(function(){
    $("#submit").click(function(e){
        e.preventDefault();

        var status = $('form')[0].checkValidity();
        if(status){
            var formData = new FormData($('form')[0]);

            $.ajax({
                url: "form_citizenship.php",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                dataType: "JSON",   

                success: function(json){
                    if(json.error){
                        alert(json.error_msg);
                    }else{
                        alert(json.docno);
                    }
                },

                error: function(jqXHR, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });
        }

    });
});

并像这样处理您的 AJAX 请求:

<?php
    session_start();
    define('HOST','localhost');
    define('USER','root');
    define('PASS','');
    define('DB','miisky');

    $response = array();

    $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

    if(!mysqli_connect_errno()){

        $error_flag = false;
        foreach($_POST as $value){
            if(empty($value)){
                $error_flag = true;
                break;
            }
        }

        if(!$error_flag){

            //receiving post parameters
            $ca =$_POST['ca'];
            $hno = trim($_POST['hno']);
            $rno = trim($_POST['rno']);
            $location = trim($_POST['location']);
            $country = trim($_POST['country']);
            $state = trim($_POST['state']);
            $city = trim($_POST['city']);
            $pin = trim($_POST['pin']);
            $doctitle = trim($_POST['doctitle']);
            $docno = trim($_POST['docno']);
            $ia = trim($_POST['ia']);
            $doe = trim($_POST['doe']);
            $pno = trim($_POST['pno']);
            $pissuedby = trim($_POST['pissuedby']);
            $pdoe = trim($_POST['pdoe']);
            $vno = trim($_POST['vno']);
            $vissuedby = trim($_POST['vissuedby']);
            $vdoe = trim($_POST['vdoe']);

            if(isset($_FILES["doc"]["name"]) && !empty($_FILES["doc"]["name"])){

                //image insertion
                $target_dir = 'doc_uploads/';
                $target_file = $target_dir . basename($_FILES["doc"]["name"]);

                $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

                $check = getimagesize($_FILES["doc"]["tmp_name"]);
                if($check !== false){

                    if (!file_exists($target_file)){

                        if($_FILES["doc"]["size"] <= 2097152){

                            $permissible_images = array('jpg', 'png', 'jpeg', 'gif');
                            if(in_array($imageFileType, $permissible_images)){

                                if (move_uploaded_file($_FILES["doc"]["tmp_name"], $target_file)){

                                    // create a new user profile
                                    $sql = "INSERT INTO citizen_info(ca, hno, rno, location, country, state, city, pin, doctitle, docno, ia, doe, pno, pissuedby, pdoe, vno, vissuedby, vdoe, doc, created_at) VALUES ('$ca', '$hno', '$rno', '$location', '$country', '$state', '$city', '$pin', '$doctitle', '$docno', '$ia', '$doe', '$pno', '$pissuedby', '$pdoe', '$vno', '$vissuedby', '$vdoe', '$target_file', NOW())";
                                    if(mysqli_query($con,$sql)){
                                        $response["error"] = false;
                                        $response['docno'] = $docno;
                                        echo json_encode($response);

                                    }else{
                                        $response["error"] = true;
                                        $response["error_msg"] = "INSERT operation failed";
                                        echo json_encode($response);
                                    }
                                }else{
                                    // Throw Error Here
                                    $response["error"] = true;
                                    $response["error_msg"] = "File could not be uploaded";
                                    echo json_encode($response);
                                }

                            }else{
                                $response["error"] = true;
                                $response["error_msg"] = "Only jpg, png and gif images are allowed";
                                echo json_encode($response);
                            }

                        }else{
                            $response["error"] = true;
                            $response["error_msg"] = "file size is above 2MB";
                            echo json_encode($response);
                        }

                    }else{
                        $response["error"] = true;
                        $response["error_msg"] = "file already exists";
                        echo json_encode($response);
                    }

                }else{
                    $response["error"] = true;
                    $response["error_msg"] = "invalid image format";
                    echo json_encode($response);
                }

            }else{
                $response["error"] = true;
                $response["error_msg"] = "Empty file";
                echo json_encode($response);
            }

        }else{
            $response["error"] = true;
            $response["error_msg"] = "Few fields are missing";
            echo json_encode($response);
        }

    }else{
        $response["error"] = true;
        $response["error_msg"] = "Database connection failed";
        echo json_encode($response);
    }
?>

【讨论】:

  • 谢谢您,先生...还有很多事情要做和学习...!!!谢谢你的一切
  • @krishna 很高兴我能帮上忙。 :)
  • 先生你能帮忙..!!上面的代码在执行时仍然显示“缺少几个字段”。
  • @krishna 那是因为您可能将一个或多个输入字段留空。所有字段均为必填项。填写所有输入字段,选择要上传的图像,然后点击保存按钮。
  • @krishna 很高兴听到。 :)
【解决方案2】:

这主要是由于 javascript 需要一个 json 响应,而服务器抛出了一些带有 '&lt;html&gt;&lt;/html&gt;' 的错误。

检查 chrome 检查器内部的 ajax 响应是否正确。 提示:

Chrome 内部&gt; F12 &gt; 网络&gt; XHR。

检查响应如下..

              $.ajax({
                url: "form_citizenship.php",
                type: "POST",
                //form serialization of the all parameters
                data: $("#form").serialize(),
                async: false,
                //data passed in json
                dataType: "JSON",
                /*Give out the alert box
                to display the results*/                
                success: function (json){
                    console.log(json); // <<< you can view in the console the response.
                    .......
                },
                //through out error from back-end if exist
                error: function(jqXHR, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });

【讨论】:

  • 但是先生,当我直接以 html 中的 form_citizenship.php 形式进行操作时,它以 json 格式给出结果..!!
  • 尝试console.log(ing) "json" 成功返回变量。看看数据是否正确就是正确的json。
  • 我是新手,请问我怎么知道..??
  • 更新了我的答案,我仍然无法理解,你为什么要在成功函数上调用$('#form').submit();,因为进行 ajax post 调用的重点是“发布”序列化的表单数据,所以在某种程度上,您只是重复发布表单。
  • 好的,但是,发生的事情是输出了两个json_encode echo,您应该首先创建一个包含您希望回显的所有数据的数组/对象然后@987654329 @ 并回显它。为了更安全,在json_encode 之后添加一个die();,这样php 执行就会立即停止。
猜你喜欢
  • 2014-03-31
  • 1970-01-01
  • 2013-09-26
  • 1970-01-01
  • 2019-03-11
  • 2022-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多