我正在尝试将带有JSON文件的AJAX请求发送到我的NodeJS服务器,但是它抛出了看起来像JSON格式错误的客户端。
错误消息
SyntaxError: Unexpected token S in JSON at position 0 at parse (<anonymous>) at Nb (jquery-3.1.1.min.js:4) at A (jquery-3.1.1.min.js:4) at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4)
脚本:
<script>
function SendToServer() {
var textToSubmit = document.getElementById("SubmitDataEntry").value;
var objectData = {
submittedText: textToSubmit,
column2: "Mitochondria is the powerhouse of the cell",
};
var objectDataString = JSON.stringify(objectData);
$.ajax({
type: "POST",
url: "/",
dataType: "json",
data: {
o: objectDataString,
},
success: function (data) {
alert("Success");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
// alert("Error");
},
});
}
</script>
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>AJAX Test</title>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
</head>
<body>
<div class="form-group" style="margin-top: 40px; padding: 50px;">
<label for="SubmitDataEntry">Submit My Data</label>
<input
type="text"
class="form-control"
id="SubmitDataEntry"
placeholder="Example input"
/>
<button onclick="SendToServer()">
Submit
</button>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</body>
</html>
到目前为止,我已经检查了我要发送的JSON的JSON,并验证了我的Node服务器可以使用Insomnia Core接收请求。我相信我的JQuery导入也可以正常工作,因为引发的错误是从那里发出的!