[Solved] ajax Error: Uncaught SyntaxError: Unexpected end of JSON input

To record, the Ajax request is as follows:

		let xhr = new XMLHttpRequest();
        xhr.open("get","https://music.kele8.cn/search");
        xhr.send();
       
        xhr.onreadystatechange = function () {
            // Determine when the Ajax status code is 4 
            if (xhr.status==200) {
                // Get the response data from the server side
                let ans = JSON.parse(xhr.responseText);
                console.log(ans);
            }
			else {
				console.log("Request failed");
			}
        }

If you ensure that the data returned in the background is correct, the get request can be opened in the browser address bar to see the data in JSON format, but the console reports an error and the data is also obtained, it may be that you lack a judgment

Look at the following code:

let xhr = new XMLHttpRequest();
xhr.open("get", "https://music.kele8.cn/search?keywords="+str);
xhr.send();
                        
xhr.onreadystatechange = function () {
     if(xhr.readyState == 4) {
            if(xhr.status == 200) {
                let arr = xhr.responseText;
                let ctype = xhr.getAllResponseHeaders("content-type");
                if(ctype.indexOf("json") > -1) {
                         let res = JSON.parse(arr);
                         console.log(res);
                 }
                 else {
                        console.log(arr);
                }
          }
          else {
                reject('Request failed');
          }
      }
}

It seems that you need to judge XHR in the onreadystatechange event If the readyState attribute is not judged, an error will be reported by JSON

Read More: