简体   繁体   English

JSON 中位置 0 处的意外标记 N 使用 ajax

[英]Unexpected token N in JSON at position 0 using ajax

I'm getting "Unexpected token N in JSON at position 0" for ajax & php coding files.对于 ajax 和 php 编码文件,我收到“位置 0 处的 JSON 中的意外标记 N”。 Can someone help me solve this?有人可以帮我解决这个问题吗? I've just started coding.我刚开始编码。

I can get the query to work and insert data, if the datatype is text.如果数据类型是文本,我可以让查询工作并插入数据。 But when I try to get the data, the result of echo stuff from php file shows up for function(data).但是当我尝试获取数据时,来自 php 文件的 echo 内容的结果显示为 function(data)。 What can I do?我能做什么?

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Build an API</title>
    <style>
        .btn {
            border: 1px solid black;
            padding: 10px;
            display: inline-block;
        }
    </style>

</head>

<body> 

ID :
    <input type="number" name="xid" id="xid" value="1">
    <br> Name :
    <input type="text" name="name" id="name" value="tester">
    <br> Company :
    <input type="text" name="company" id="company" value="company">
    <br> Cost :
    <input type="number" name="cost" id="cost" value="10">
    <br>
    <div class='btn' id="btn1">Send Data</div>
    <div class='btn' id="btn2">Get Data</div>

    <div id="result"></div>
    <div id="sample"></div>



    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
    <script>
        $(function () {
            //FIRST BUTTON
            $('#btn1').on('click', function () {
                var vars = {
                    xid: $('#xid').val()
                    , name: $('#name').val()
                    , company: $('#company').val()
                    , cost: $('#cost').val()
                    , action:'ADD'
                }
                $.ajax({
                    url: "api.php"
                    , data: vars
                    , type: "POST"
                    , dataType: 'json'
                }).done(function (data) {
                    $("#result").html(data).message;
                    console.log(data);
                    alert('DONE: ' + data);
                }).fail(function (xhr, textstatus,errorThrown) {
                    console.log(xhr);
                    console.log(textstatus);
                    //alert('xhr, textstatus: ' + xhr + textstatus);
                    alert("errorThrown    : " + errorThrown.message);
                    console.log("errorThrown    : " + errorThrown.message);
                })
            })
        })
    </script>
</body>

</html>


<?php
header('Content-Type: application/json; charset=utf-8');

$con = new mysqli("localhost","[name]","[password]","myDB");
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}
$arr = [];

if($con->ping()){$arr['connected']=true;}else{$arr['connected']=false;}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $arr['xid'] = $_POST['xid'];
    $arr['name'] = $_POST['name'];
    $arr['company'] = $_POST['company'];
    $arr['cost'] = $_POST['cost'];   
    $arr['action'] = $_POST['action'];    
}else{
    $arr['xid'] = '100';
    $arr['name'] = 'noname';
    $arr['company'] = 'company';
    $arr['cost'] = '100';    
    $arr['action'] = 'ADD';
}

$xid = $arr['xid'];
$name = $arr['name'];
$company = $arr['company'];
$cost = $arr['cost'];  

if($arr['action']=='ADD'){   
    if(isset($xid) && isset($name) && isset($company) && isset($cost)){
        $sql = "INSERT INTO api (xid, cost, name, company) VALUES ('$xid', '$cost', '$name', '$company')";
        if (mysqli_query($con, $sql)) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . mysqli_error($con);
        }
        mysqli_close($con);
    }
}   
?>

With this you announce that the response will be in JSON format:有了这个,您宣布响应将采用 JSON 格式:

header('Content-Type: application/json; charset=utf-8');

But a few lines later you return plain text:但是几行之后你返回纯文本:

echo "New record created successfully";

Either you change the header to要么将标题更改为

header('Content-Type: text/plain; charset=utf-8');

or you change the response to something like this或者您将响应更改为这样的

echo json_encode(["message"=>"New record created successfully"]);

since you put the dataType: 'json' in javascript, so you have to put all the returns from the php page (success and failure returns) with json_encode("...");由于您将dataType: 'json'放在 javascript 中,因此您必须将 php 页面的所有返回(成功和失败返回)与json_encode("...");

OR或者

change dataType: 'json' to dataType: 'text' in javascript在 javascript 中将dataType: 'json'更改为dataType: 'text'

and change in php并更改 php

header('Content-Type: application/json; charset=utf-8');

to

header('Content-Type: text/plain; charset=utf-8');

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM