使用AJAX/JavaScript调用URL时出现500错误,求排查原因
问题描述
尝试将外部JSON文件引入JavaScript代码,通过在线服务生成接口URL(原生成地址为https://api.jsonserve.com/Xljpm),使用XMLHttpRequest调用该URL时出现错误,但调用本地服务器上的同数据JSON文件正常。开发工具为Visual Studio Code。
执行代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JSON Giantess Data External</title> </head> <body> <style> #output { background-color: blue; font-family: Arial, Helvetica, sans-serif; font-size: 16px; font-weight: bold; } </style> <div id="output" class="oput">Nothing</div> <script> var myContainer = ""; var a = new XMLHttpRequest(); a.open("GET", "https://api.jsonserve.com/Xljpml", true); //a.open("GET","data.json",true); a.onreadystatechange = function() { if (this.readyState == 4) { var obj = JSON.parse(this.responseText); for (i = 0; i < obj.length; i++) { console.log(obj[i]); myContainer += obj[i].giantess + " is growing to be " + obj[i].height + "!!!" + "<br>"; } document.getElementById("output").innerHTML = myContainer; console.log(obj); } } a.send(); </script> </body> </html>
错误信息
AJAX_JSON.html:38 GET https://api.jsonserve.com/Xljpml 500 (anonymous) @ AJAX_JSON.html:38 VM181:1 Uncaught SyntaxError: Unexpected token 'I', "Internal S"... is not valid JSON at JSON.parse (<anonymous>) at a.onreadystatechange (AJAX_JSON.html:29:19) a.onreadystatechange @ AJAX_JSON.html:29 XMLHttpRequest.send (async) (anonymous) @ AJAX_JSON.html:38 AJAX_JSON.html:1 Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
问题原因
- URL拼写错误:你生成的接口地址是
https://api.jsonserve.com/Xljpm,但代码里写的是https://api.jsonserve.com/Xljpml,多了一个末尾的l,这会导致请求到不存在的资源,触发服务器500内部错误。 - 非JSON响应导致解析失败:因为URL错误,服务器返回的是"Internal Server Error"这类文本信息,而非预期的JSON数据,执行
JSON.parse()时自然会抛出语法错误。 - 异步响应错误是连锁问题:最后那条关于异步响应的错误是浏览器的附加提示,根源还是前面的请求失败导致后续流程异常,解决URL问题后这条错误会自动消失。
内容的提问来源于stack exchange,提问作者MLB06
相关产品推荐
相关产品推荐

