简体   繁体   English

jQuery ajax语法错误json.parse json数据的第1行第1行出现意外字符

[英]Jquery ajax syntaxerror json.parse unexpected character at line 1 column 1 of the json data

I have this web application that I just use four scripts that is a dynamical. 我有一个仅使用四个动态脚本的Web应用程序。

Brief: 简要:

  • Init.php = Database, Init.php =数据库,
  • index.php = webpage, index.php =网页,
  • api.php = grabs info from server/post info to server, api.php =从服务器获取信息/将信息发布到服务器,
  • drive.js = grabs info from api.php and displays it to index.php or when post, went to api.php drive.js =从api.php获取信息并将其显示为index.php或在发布时转到api.php

So I'm just trying to add a person through post method by jquery ajax. 所以我只是想通过jquery ajax通过post方法添加一个人。 But I have this syntaxerror in my code, which mainly goes to my drive.file of addPerson function: 但是我的代码中有这个语法错误,主要是我的addPerson函数的drive.file:

json.parse unexpected character at line 1 column 1 of the json data json.parse json数据第1行第1行的意外字符

    // populate people/states, also person/visit form submit
    $(document).ready(function(){
        populatePeople();
        populateStates();
        displayData();

        $('#addPersonSubmit').click(function(e){
            e.preventDefault();
            addPerson();
        });

        $('#addVisitSubmit').click(function(e){
            e.preventDefault();
            addVisit();
        });
    });

    //display selected person
    function displayData()
    {
        $("#SelectHumanDropDown").change(function(){
            $.ajax({
                type: "GET",
                url: "api/visits",
                dataType: "json",
                success: function(data)
                {
                    var i = $("#SelectHumanDropDown").val();
                    $("#displayInfo").empty();

                    var firstName = data[i]["firstname"];
                    var lastName = data[i]["lastname"];
                    var food = data[i]["food"];
                    var stateAbb = data[i]["stateabb"];
                    var stateName = data[i]["statename"];
                    var dateVisit = data[i]["date_visited"];

                    $("#displayInfo").append(
                    "First name: " + firstName +
                    "<br> Last name: " + lastName +
                    "<br> Favorite food: " + food +
                    "<br> Visited : " + stateAbb + " " + stateName +
                    "<br> on " + dateVisit);
                }
            });
        });
    }

    //populate people's dropdowns
    function populatePeople()
    {
        $.ajax({
            type:"GET",
            url:"api/people",
            dataType:"json",
            success : function(data)
            {
                //console.log('success');
                //console.log(data);
                $("#SelectHumanDropDown").empty();
                $("#humanNameDropDown").empty();
                var len = data.length;
                for(var i = 0; i < len; i++)
                {
                    var id = data[i]["id"];
                    var firstname = data[i]["firstname"];
                    $("#SelectHumanDropDown").append("<option value='" + id + "'>" + firstname + "</option>");
                    $("#humanNameDropDown").append("<option value='" + id + "'>" + firstname + "</option>");
                }
            },
            error : function(data)
            {
                console.log('failed');
                console.log(data);
            }
        });
    }

    //populate state dropdown
    function populateStates()
    {
        $.ajax({
            type:"GET",
            url:"api/states",
            dataType:"json",
            success : function(data)
            {
                //console.log('success');
                //console.log(data);
                $("#stateNameDropDown").empty();
                var len = data.length;
                for(var i = 0; i < len; i++)
                {
                    var id = data[i]["id"];
                    var stateName = data[i]["statename"];
                    $("#stateNameDropDown").append("<option value='" + id + "'>" + stateName + "</option>");
                }
            },
            error : function(data)
            {
                console.log('failed');
                console.log(data);
            }
        });
    }

        //Add person to database
        function addPerson()
        {
            $.ajax({
                type: "POST",
                url: "api/people", // api/people
                data: $("#personForm").serialize(),
                 success: function(data,status,xhr)
                {
                    console.log(data);
                    console.log(status);
                    console.log(xhr);
                    console.log($("#personForm").serialize());
                    console.log("You have added a person");
                    populatePeople();
                    displayData();
                },
                 error: function(data,status,xhr)
                {
                    console.log(data);
                    console.log(status);
                    console.log(xhr);
                    console.log($("#personForm").serialize());
                    console.log("error");
                    //populatePeople();
                    //displayData();
                }
            });
       }

        //Add visit to database
    function addVisit()
    {
        $.ajax({
            type: "POST",
            url: "api/visits", // api/visits
            data: $("#humanNameDropDown, #stateNameDropDown, #visitForm").serialize(),
            success: function(data)
            {
                console.log(data);
                console.log($("#visitForm").serialize());
                console.log("You have added a visit");
            },
            error: function(data)
            {
                console.log(data);
                console.log($("#visitForm").serialize());
            }
        });
    }

I also have my database which is init.php 我也有我的数据库init.php

        <?php
    // Define variables. 
    $host = "localhost";
    $user = "root";
    $password = "root";
    $database = "myDB";

    //Create connection
    $connection = mysqli_connect($host, $user, $password);

    // Check connection
    if(!$connection){
    die("Could not connect: " . mysqli_connect_error());}
    else{
        echo "Connection successfully \n";
    }

    // Drop database
    $dropDB = "DROP DATABASE myDB";

    // Check drop database
    if($connection->query($dropDB) === TRUE){
         echo "Database myDB was successfully dropped \n";
    } else {
        echo "Error dropping database: \n" . $connection->error;
    }

    //Create Database called "myDB"
    $db = "CREATE DATABASE IF NOT EXISTS myDB";

    //Check Datebase
    if($connection->query($db) === TRUE){
        echo "Database created successfully \n";
    } else {
        echo "Error creating database: \n" . $connection->error;
    }

    // Select Database
    $connection->select_db($database);

    //Create States Table
    $statesTable = "CREATE TABLE IF NOT EXISTS States
    (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    stateabb varchar(2) NOT NULL,
    statename varchar(40) NOT NULL
    )";

    // Create People Table
    $peopleTable = "CREATE TABLE IF NOT EXISTS People
    (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    firstname varchar(40) NOT NULL,
    lastname varchar(40) NOT NULL,
    food varchar(40) NOT NULL
    )";

    // Create Visit Table
    $visitTable = "CREATE TABLE IF NOT EXISTS Visits
    (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    p_id INT(40) NOT NULL,
    s_id INT(40) NOT NULL,
    FOREIGN KEY (p_id) REFERENCES People(id),
    FOREIGN KEY (s_id) REFERENCES States(id),
    date_visited varchar(40) NOT NULL
    )";

    //Check States Table
    if($connection->query($statesTable) === TRUE) 
    {
        echo "States Table created successfully \n";
    }
    else
    {
        echo "States Table wasn't created \n" . $connection->error;
    }

    //Check People Table
    if($connection->query($peopleTable) === TRUE) 
    {
        echo "People Table created successfully \n";
    }
    else
    {
        echo "People Table wasn't created \n" . $connection->error;
    }

    //Check Visit Table
    if($connection->query($visitTable) === TRUE) 
    {
        echo "Visit Table created successfully \n";
    }
    else
    {
        echo "Visit Table wasn't created \n" . $connection->error;
    }

    // Insert data into states table
    $insertData = " INSERT INTO States (stateabb, statename) 
                    VALUES ('LA', 'Louisiana');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('FL', 'Florida');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('TX', 'Texas');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('NM', 'New Mexico');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('ID', 'Idaho');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('IA', 'Iowa');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('ME', 'Maine');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('NV', 'Nevada');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('NY', 'New York');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('UT', 'Utah');";

    // Insert data into people table
    $insertData .= "INSERT INTO People (firstname, lastname, food) 
                    VALUES ('Paul', 'Chu', 'Rice');";
    $insertData .= "INSERT INTO People (firstname, lastname, food) 
                    VALUES ('Chui', 'Chu', 'Steak');";
    $insertData .= "INSERT INTO People (firstname, lastname, food) 
                    VALUES ('Pandalord', 'Chu', 'Cookies');";
    $insertData .= "INSERT INTO People (firstname, lastname, food) 
                    VALUES ('LordBabyPanda', 'Chu', 'Milk');";

    // Insert data into Visits table
    $insertData .= "INSERT INTO Visits (p_id, s_id, date_visited) 
                    VALUES ('1', '1', '1994/07/14');";
    $insertData .= "INSERT INTO Visits (p_id, s_id, date_visited) 
                    VALUES ('1', '2', '1994/07/14');";
    $insertData .= "INSERT INTO Visits (p_id, s_id, date_visited) 
                    VALUES ('2', '10', '1994/07/14');";
    $insertData .= "INSERT INTO Visits (p_id, s_id, date_visited) 
                    VALUES ('3', '9', '1994/07/14');";
    $insertData .= "INSERT INTO Visits (p_id, s_id, date_visited) 
                    VALUES ('4', '7', '1994/07/14');";

    // Check stateData in table
    if($connection->multi_query($insertData) === TRUE)
    {
        $lastID = $connection->insert_id;
        echo "insertData create successfully. Last inserted ID is: \n" . $lastID;
    }

    else
    {
        echo "Error: \n" . $connection->error;
    }

    //Close Connection
    $connection->close();
    ?>

Also, I have my index.php and api.php as links so this page wouldn't be dreadful long. 另外,我将index.php和api.php作为链接,因此此页面不会太长。

index.php 的index.php

api.php api.php

So, hello everyone, I figured out my own problem but with help with @RoryMcCrossan, 所以,大家好,我想出了自己的问题,但是在@RoryMcCrossan的帮助下,

So when I checked for my responseText it was undefined . 因此,当我检查我的responseText它是undefined But then I remembered it was a parsing error, so I look through the web, and I saw someone had a similarly case, but they echo json_encode() their data back when they post. 但是后来我记得这是一个解析错误,所以我浏览了整个网络,发现有人也遇到了类似的情况,但是他们在发布时echo json_encode()数据。

So I did the same thing to test it and it works! 所以我做了同样的事情来测试它,而且效果很好! So happy. 很高兴。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SyntaxError:JSON.parse:JSON数据第3行第1列的意外字符 - SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data SyntaxError:JSON.parse:JSON数据的第1行第2列出现意外字符 - SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符吗? - SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data? 语法错误json.parse json数据第1行第1列的意外字符 - syntaxerror json.parse unexpected character at line 1 column 1 of the json data 语法错误:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符 - SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 具有相同数据的Ajax错误(parsererror:SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符) - Ajax error with the same data (parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data) SyntaxError: JSON.parse: JSON 第 1 行第 2 列的意外字符 - SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON AJAX SyntaxError:JSON.parse:意外字符 - AJAX SyntaxError: JSON.parse: unexpected character JSON错误:SyntaxError:JSON.parse:JSON数据的第2行第1列出现意外字符 - JSON error : SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data Jquery - Ajax:SyntaxError:JSON.parse:意外字符 - Jquery - Ajax: SyntaxError: JSON.parse: unexpected character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM