This problem is encountered in spring MVC and JSP simulating asynchronous requests of Ajax.
Complete error message:
JSON parse error: Unexpected character (''' (code 39)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): was expecting double-quote to start field name
Error reason: the format of JSON in the front-end Ajax request is incorrect. The outer part of the array should be wrapped in single quotation marks, and the inner key & amp; Value pairs are enclosed in double quotes.
As shown below.
$.ajax(
{
url:"testAjax",
contentType:"application/json;charset=UTF-8",
//Right
data:'{"username":"zs","password":"12456","age":"18"}',
//Wrong
data:"{'username':'zs','password':'12456','age':'18'}",
dataType:"json",
type:"post",
success:function (data) {
// data is the server-side response data
alert(data);
alert(data.username)
}
}
In the practice of spring MVC, many people may encounter this annoying problem, it took a long time to solve, the code is right, but he just reported an error content type ‘application/JSON’ not supported I have found many articles on the Internet and used many methods, but they can’t solve this problem finally, I remembered if I didn’t add the jar package required by JSON in lib, so I tried it… It was a success indeed the following is my method
because I have added it, so here you can see that there are three jar packages in my lib package, just add these three packages~~~
Because AJAX is executed asynchronously by default, that is, the next line of JS statement is executed without waiting for the request to finish, resulting in null assignment.
Today, when I was working, I encountered a problem. I used $. Ajax to transfer data to the background, which can operate correctly in the background, but success did not respond, and error responded. After checking the document, I realized that after jQuery version 1.4, all the returned JSON formats must meet the requirements json.org Success can only be called back correctly in the format of, otherwise jQuery will think that it returns an error Here is an example:
JSONObject j = new JSONObject();
j.put("msg","SUCCESS");
PrintWriter out = response.getWriter();
out.write(j.toString());
This is correct. JQuery calls back success
String j = "123";
PrintWriter out = response.getWriter();
out.write(j);
Recently, I encountered such a function when I was working on a website. In the page as shown in the figure, when users need to click the link, they can judge whether the corresponding excel file is stored in the server in an asynchronous ajax way. If not, they will be prompted that they have not found it, and if so, they will download it to the local user.
Of course, this is a very simple problem. Just write Ajax in a normal way. But when the server returns the file content to the browser in binary form, the browser’s Ajax throws an error. It’s about parseError, invalid XML, PK, etc.
The reason for this problem is not that there is a problem with the server-side code or JavaScript code, but that downloading files through AJAX is forbidden. For security reasons, JavaScript is not able to save the file to the local, so Ajax takes this into account. It only accepts the return value in XML, Ajax and JSON format, and the binary return format will throw this exception.
How to solve this problem?use window.location =URL is OK. Some people will ask, such as the above figure, when you click the download link on a certain page, because it has changed window.location Is the current page about to jump?In fact, I use Chrome browser. When I click that link, the next file save dialog box will pop up directly, and the address bar of the page has no change. At this time, if you click save, the file will be kept. If you click cacel, the operation will be cancelled. During the process, the current page will be kept and will not jump to other pages.
1. Problem Description: cross domain problem in front end call interface
2. Solution, add the following classes
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.allowedOrigins("*");
}
};
}
}
The <> <<<<<<<<<<<<<<<<<<<<< <<< <<<< << <<<<<<<< <<<<<<<<<
> access control allow- Credentials
allowedheads
string array
class or interface
no
access control request heads
exposed heads
string array
class or interface
no
access control expose heads
Note:
1) Attribute value, origins: configure the sources that can be accessed, for example: 0 https://adong.blog.csdn.net/article/details/113126033 * indicates that all domain names are allowed.
2) Property methods: configure the methods of cross domain request support, such as get, post, delete, put, and return all supported methods at one time.
3) Attribute maxage: configures the valid time of the pre check request. The unit is seconds. It indicates how long the second pre check request does not need to be issued.
4) Attribute allowcredentials: configure whether to allow sending cookies for credential requests. Cookies are not sent by default.
5) Attribute allowedheaders: configure the allowed custom request headers for pre checking requests.
6) Attribute exposedheaders: configure the header information of the response, in which other header information can be set. Without configuration, cache control, content language, content type, expires, last modified and pragma fields can be obtained by default.
Jackson-core-asl-1.9.12.jar Jackson-mapper-asl-1.9.12.jar
The test is not for this error and does not have to rely on the two JARs.
The following configuration returns data normally
——————————————————————————-
The ResultDTO object is missing some of the GET methods, causing an error in formatting the JSON object.
Remove the above two JARs and test with the GET method of the returned object, reporting 406 error code.
The debug code in ServletInvocableHandlerMethod. Catch exceptions in the class “Could not find acceptable representation.” ”
After adding the get method, the test returns the JSON character of the object normally
public class ResultDto {
private boolean succeed;
private Object data;
public ResultDto(boolean succeed) {
this.succeed = succeed;
}
public ResultDto(boolean succeed, Object data) {
this.succeed = succeed;
this.data = data;
}
/*
public boolean isSucceed() {
return succeed;
}
public Object getData() {
return data;
}
*/
public void setSucceed(boolean succeed) {
this.succeed = succeed;
}
public void setData(Object data) {
this.data = data;
}
}
A quick introduction to Ajax:
Simply put, an Ajax request sends a request through an XMLHttpRequest object, which has four states (readyStates) :
0- uninitialized, 1- initializing, 2- sending data, 3- sending data, 4- done.
When XMLHttpRequest. ReadyState is 4, said ajax request has been completed can get the result.
Ajax’s success and Error methods are triggered based on the response status code. Success () is triggered when XMLHttprequest.status is 200, indicating a successful response. Other status codes trigger error().
In addition to the response status code, Ajax can also use an error method in the following situations:
return data type is not JSON network interrupt background response interrupt
Microsoft JScript Runtime Error: ‘Sys’ is undefined solution
Want to learn AJAX system, unexpectedly just drag a ScriptMange, appeared “Microsoft JScript runtime error: ‘Sys’ is undefined” error, Google a, found that the original friends have also encountered a similar error, put the method post,
ajax.net1.0 official version in web.config–> Add < httpHandlers> < remove verb=”*” path=”*.asmx”/> & lt; add verb=”*” path=”*.asmx” validate=”false” type=”System.Web.Script.Services.ScriptHandlerFactory”/> & lt; Add the verb = “the GET and HEAD” path = “ScriptResource. Axd” type = “System. Web. Handlers. ScriptResourceHandler, System. Web. Extensions, Version = 1.0.61025.0, Culture = neutral, PublicKeyToken=31bf3856ad364e35” validate=”false”/> & lt; /httpHandlers>
If our js file contains Ajax code, and references the HTML file of this js file, open the test directly locally, this error will appear:
as shown below:
util. Js file
function ajax(url,options,type){
var oAjax=null;
var type=type || "GET";
//alert(type);
if(window.XMLHttpRequest){
oAjax=new XMLHttpRequest();
}
else{
oAjax=new ActiveXObject('Microsoft.XMLHTTP');
}
oAjax.onreadystatechange=function(){
if (oAjax.readyState==4) {
if (oAjax.status==200) {
options.onsuccess(oAjax.responseText);
}
else{
options.onfail();
};
};
}
url=url+"?name="+options.data.name+"&password="+options.data.password+"&t="+Math.random();
oAjax.open(type,url,true);
oAjax.send();
}
Assuming that there are other functions in the util.js file that we need, when we introduce util.js into the HTML file, the local browser opens the test with an error
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>task0002</title>
<script type='text/javascript' src='js/util.js'></script>
</head>
<body>
<textarea name="hobby" id="hobby" cols="30" rows="10"></textarea><br/>
<input type="button" id='btn' value='filtration'>
<script>
var oTxt=document.getElementById('hobby');
var btn=document.getElementById('btn');
var p=document.createElement('p');
document.body.appendChild(p);
btn.onclick=function(){
var hobbys=oTxt.value;
var ary=hobbys.split(/[,、;\n\s,\u3000]/);
ary=uniqArray(ary);
p.innerHTML="";
p.innerHTML="hobby:"+ary.join("<br/>");
}
</script>
</body>
</html>
The reason: When local browsing opens the page, a cross-domain problem occurs, so the message is that you don’t have permission
Solution:
1. Put the ajax code part in the HTML file, there will be no problem
2. By placing the project folders on the server, they will be in one domain by default and cross-domain problems will not occur