简体   繁体   English

未捕获到的SyntaxError:JSON中位置0处的意外令牌

[英]Uncaught SyntaxError: Unexpected token in JSON at position 0

With some help, I have managed to make a form that validates and confirms user password before adding the user to the database. 在一些帮助下,我设法制作了一个在将用户添加到数据库之前验证并确认用户密码的表单。 I have encountered some problem as the data of the user is not sent and giving me the following error : 我遇到了一些问题,因为未发送用户数据,并给我以下错误:

Uncaught SyntaxError: Unexpected token in JSON at position 0 未捕获到的SyntaxError:JSON中位置0处的意外令牌
at JSON.parse () 在JSON.parse()
at Object.success (confirm3.php:29) 在Object.success(confirm3.php:29)
at i (jquery.min.js:2) 在我(jquery.min.js:2)
at at A (jquery.min.js:4) 在A处(jquery.min.js:4)
at XMLHttpRequest. 在XMLHttpRequest。 (jquery.min.js:4) (jquery.min.js:4)

The error 错误

at Object.success (confirm3.php:29) 在Object.success(confirm3.php:29)

is referring to this following line 指的是这一行

var data = JSON && JSON.parse(response) || $.parseJSON(response);

The POST variable POST变量

$UserNm=$_POST["UserNm"];
$UserId=$_POST["UserId"];
$UserPwd=$_POST["UserPwd"];

To make things clear, the data that should be returned is $ReturnMessage which is retrieved from stored procedure. 为了清楚$ReturnMessage ,应返回的数据是$ReturnMessage ,该数据从存储过程中检索。 $ReturnMessage will display the status of the operation for both successful and fail operation. $ReturnMessage将显示成功和失败操作的操作状态。

An example of $ReturnMessage : $ReturnMessage的示例:

"USER ID EXIST. (011 CODE)." “用户标识已存在。(011代码)。”
"USER ID MINT20 ADDED." “添加了用户ID MINT20。”

POST method is used : if(isset($_POST['Submit'])) { 使用了POST方法: if(isset($_POST['Submit'])) {

$ReturnMessage : $ ReturnMessage:

 if(isset($ReturnStatus) && $ReturnStatus==1) {
 $ReturnMessage=odbc_result($stmt,'ReturnMessage');
 }
 }

 $ReturnMessage = utf8_encode ($ReturnMessage);
 echo json_encode($ReturnMessage);
 }

Script : 剧本:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">
$(function() {
  $("#myForm").on("submit", function(e) {
    e.preventDefault(); 
    var password = $("#UserPwd").val();
    var confirmPassword = $("#ConfirmPassword").val();
    console.log(password,confirmPassword)  
    if ($.trim(password) === password && 
      password !== "" && 
      password === confirmPassword) { 
      $.ajax({
        url: "confirm3.php",
        method: "POST",
        data: { Submit: "true" },
        success: function(response) {
          var data = JSON && JSON.parse(response) || $.parseJSON(response);
          alert(data);
        }
        });
        } else {
          alert("Please Enter Password Correctly");
        }
      });
});
<script>

I'm kind of confuse. 我有点困惑。 Please guide me. 请指导我。 Thank you. 谢谢。

First of all, jQuery can decode JSON automatically for you (and it will make its best to guess). 首先,jQuery可以为您自动解码JSON(它将尽力猜测)。 Trying to do it manually only makes your code more verbose and error-prone. 手动进行操作只会使您的代码更加冗长且容易出错。 However, you don't give it any hint. 但是,您没有给出任何提示。 Nothing in the code you've shared gives any clue about your intention to use jQuery. 您共享的代码中没有任何有关您打算使用jQuery的线索。

All the phases where you can do so, in chronological order: 您可以按时间顺序执行的所有阶段:

  1. Report data type from web server. 从Web服务器报告数据类型。 If you happen to be using Apache: 如果您碰巧正在使用Apache:

     <Files "confirm3.php"> ForceType application/json </Files> 
  2. Report data type from PHP: 从PHP报告数据类型:

     header('Content-Type: application/json'); 
  3. Tell jQuery that you expect JSON: 告诉jQuery您需要JSON:

     url: "confirm3.php", method: "POST", dataType: "json", data: { Submit: "true" }, success: function(response) { console.log(data); // Already decoded (don't use alert to debug!) } 

You can certainly omit almost any step, but not all. 您当然可以忽略几乎任何步骤,但不能全部。

Secondly, if you get a JSON parse error the very first you need to check is whether the response is valid JSON. 其次,如果收到JSON解析错误,则首先需要检查响应是否为有效JSON。 The most straightforward way to see it is using the browser developer tools, more specifically the "Network" pane . 最直观的查看方法是使用浏览器开发人员工具,尤其是“网络”窗格

Have you set your content-type in your php? 您是否在php中设置了内容类型?

header('Content-Type: application/json');

Also you don't need to put "true" in quote marks, when the json gets to your php script, once you run json_decode, php will recognise it as a boolean. 另外,您无需在引号中加上“ true”,当json进入您的php脚本时,一旦运行json_decode,php就会将其识别为布尔值。

Use this in my case there was some null bytes so this i figured out and it fixed my issues. 在我的情况下使用它,因为有一些空字节,所以我弄清楚了,它解决了我的问题。

var data3 = data.substring(data.lastIndexOf("{")+1,data.lastIndexOf("}"));
      count = $.parseJSON("{"+data3+"}");
      alert( count.firstname ); // firstname is the key so you can use anything to test it.

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

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