需要一些帮助来找出页面加载时抛出的 JSON.parse 错误。
Uncaught SyntaxError: Unexpected token m in JSON at position 0 at JSON.parse ()
这只是 Mastercard 支付网关中提供的示例代码 documentation .我正在尝试使用商家提供的测试数据对其进行测试。我通过验证器运行代码,它没有返回任何错误。
这是我要执行的代码。
<!DOCTYPE html>
<html>
<head>
<script src="https://test-gateway.mastercard.com/checkout/version/52/checkout.js"
data-error="errorCallback"
data-cancel="cancelCallback">
</script>
<script type="text/javascript">
function errorCallback(error) {
console.log(JSON.stringify(error));
}
function cancelCallback() {
console.log('Payment cancelled');
}
Checkout.configure({
"merchant" : "TEST",
"order" : {
"amount" : 1000,
"currency" : "USD",
"description" : "Ordered goods" ,
"id" : 123
},
"interaction" : {
"operation" : "AUTHORIZE",
"merchant" : {
"name" : "ABC Hotel" ,
"address" : {
"line1" : "some road" ,
"line2" : "some city"
}
}
}
});
</script>
</head>
<body>
...
<input type="button" value="Pay with Lightbox" onclick="Checkout.showLightbox();" />
<input type="button" value="Pay with Payment Page" onclick="Checkout.showPaymentPage();" />
...
</body>
</html>
最佳答案
大多数情况下,当 JSON.parse
抛出位置 0 无效 JSON 的错误时,问题出在 Byte Order Mark (BOM)
( Wikipedia )。
为避免解析 BOM,您应该检查 JSON 字符串是否以 0xFEFF
开头,这是 BOM
的 Unicode 表示,然后手动将其删除。
例子:
let json = `{"hello":"world"}`;
// make sure you trim the JSON string before, otherwise the first character may be a whitespace
if (json.trim().charCodeAt(0) === 0xFEFF) {
json = json.slice(1); // cut the BOM character
}
const result = JSON.parse(json);
关于javascript - JSON 解析抛出的意外 token 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56823438/