[英]Uncaught SyntaxError: Unexpected token : in JSON at position 362
[英]Uncaught SyntaxError: Unexpected token in JSON at position 0
在一些幫助下,我設法制作了一個在將用戶添加到數據庫之前驗證並確認用戶密碼的表單。 我遇到了一些問題,因為未發送用戶數據,並給我以下錯誤:
未捕獲到的SyntaxError:JSON中位置0處的意外令牌
在JSON.parse()
在Object.success(confirm3.php:29)
在我(jquery.min.js:2)
在A處(jquery.min.js:4)
在XMLHttpRequest。 (jquery.min.js:4)
錯誤
在Object.success(confirm3.php:29)
指的是這一行
var data = JSON && JSON.parse(response) || $.parseJSON(response);
POST變量
$UserNm=$_POST["UserNm"];
$UserId=$_POST["UserId"];
$UserPwd=$_POST["UserPwd"];
為了清楚$ReturnMessage
,應返回的數據是$ReturnMessage
,該數據從存儲過程中檢索。 $ReturnMessage
將顯示成功和失敗操作的操作狀態。
$ReturnMessage
的示例:
“用戶標識已存在。(011代碼)。”
“添加了用戶ID MINT20。”
使用了POST方法: if(isset($_POST['Submit'])) {
$ ReturnMessage:
if(isset($ReturnStatus) && $ReturnStatus==1) {
$ReturnMessage=odbc_result($stmt,'ReturnMessage');
}
}
$ReturnMessage = utf8_encode ($ReturnMessage);
echo json_encode($ReturnMessage);
}
劇本:
<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>
我有點困惑。 請指導我。 謝謝。
首先,jQuery可以為您自動解碼JSON(它將盡力猜測)。 手動進行操作只會使您的代碼更加冗長且容易出錯。 但是,您沒有給出任何提示。 您共享的代碼中沒有任何有關您打算使用jQuery的線索。
您可以按時間順序執行的所有階段:
從Web服務器報告數據類型。 如果您碰巧正在使用Apache:
<Files "confirm3.php"> ForceType application/json </Files>
從PHP報告數據類型:
header('Content-Type: application/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!) }
您當然可以忽略幾乎任何步驟,但不能全部。
其次,如果收到JSON解析錯誤,則首先需要檢查響應是否為有效JSON。 最直觀的查看方法是使用瀏覽器開發人員工具,尤其是“網絡”窗格 。
您是否在php中設置了內容類型?
header('Content-Type: application/json');
另外,您無需在引號中加上“ true”,當json進入您的php腳本時,一旦運行json_decode,php就會將其識別為布爾值。
在我的情況下使用它,因為有一些空字節,所以我弄清楚了,它解決了我的問題。
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.