Tag Archives: ajax

[Solved] JSON parse error: Unexpected character (‘‘‘ (code 39)): was expecting double-quote to start ……

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)
                    }
                }

Springmvc Content type ‘application/json‘ not supported

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~~~

Spring MVC uses Ajax to submit requests asynchronously to complete login

Submit the form asynchronously with Ajax, log in and return the JSON data.

1、 Effect

2、 Configuration

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.it.springmvc" />

    <mvc:annotation-driven></mvc:annotation-driven>
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <mvc:default-servlet-handler/>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" 
version="3.0">
  <display-name>springMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
      <servlet-name>example</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>

Controller

PersonController.java

package com.it.springmvc.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.it.springmvc.entity.Person;

@Controller
public class PersonController {
    @RequestMapping(value="/toLogin",method=RequestMethod.GET)
    public String toLogin(){
        return "login";
    }

    @RequestMapping(value="/login",method=RequestMethod.POST)
    public String login(Person person){
        if(10025==person.getPid()&&"123".equals(person.getPwd())){
            return "redirect:queryAll";
        }else{
            return "login";
        }
    }
    @RequestMapping(value="/queryAll",method=RequestMethod.GET)
    public ModelAndView queryAll(){
        ModelAndView mav=new ModelAndView("show");
        List<Person> list=new ArrayList<Person>();
        list.add(new Person(10025, "tom", "123"));
        list.add(new Person(10026, "jakson", "123"));
        list.add(new Person(10027, "nikly", "123"));
        mav.addObject("list", list);
        return mav;
    }
    @RequestMapping("/ajax")
    @ResponseBody
    public Object ajax(Person person){
        System.out.println(person.getPid()+person.getPwd());
        if(10025==person.getPid()&&"123".equals(person.getPwd())){
            return "{\"flag\":true}";
        }else{
            return "{\"flag\":false}";

        }

    }

}

1.2.2.

Index.jsp

<body>
<%
response.sendRedirect("toLogin");
%>
</body>

login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
    $("#sub").click(function(){
        $.post("ajax",$("form").serialize(),function(data){
            //alert(data.flag);
              if(data.flag){
                alert("Login success");
                location.href="queryAll";
            }else{
                alert("please recheck your usename and password");
            } 
        },'json');
    })
})
</script>
<body>
<form  method="post">
    <table border="1" width="300px">
        <tr>
            <td>usename</td>
            <td><input type="text" name="pid"/></td>
        </tr>
        <tr>
            <td>password</td>
            <td><input type="password" name="pwd"/></td>
        </tr>
        <tr>            
            <!-- <td colspan="2"><input type="submit" value="submit"/></td> -->
            <td colspan="2"><input type="button" value="submit" id="sub"/></td>
        </tr>
    </table>
</form>

</body>
</html>

show.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="toAdd">Add</a>
<table border="1" width="400px">
    <tr>
        <th>NUM</th>
        <th>name</th>
        <th>password</th>
        <th>Act</th>
    </tr>
    <c:forEach var="person" items="${list}">
        <tr>
            <td>${person.pid }</td>
            <td>${person.pname }</td>
            <td>${person.pwd }</td>
            <td><a href="">Update</a></td>
            <td><a href="">DEL</a></td>

        </tr>
    </c:forEach>
</table>
</body>
</html>

The solution of calling$. Ajax successfully but the success method does not respond

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);

This is wrong, jQuery will think it is wrong

 

Ajax can’t download file to browser

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.

 

 

From personal blog www.sunrobin.net

 

 

Spring boot uses configuration interface webmvcconfigurer to solve cross domain problems

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.

How to download files by post submission under Ajax

/*===================Download file
 * options:{
 * url:'',  //Download Url
 * data:{name:value}, //the datas you want to post
 * method:'post'
 * }
 */
var DownLoadFile = function (options) {
    var config = $.extend(true, { method: 'post' }, options);
    var $iframe = $('<iframe id="down-file-iframe" /&>');
    var $form = $('<form target="down-file-iframe" method="' + config.method + '" /&>');
    $form.attr('action', config.url);
    for (var key in config.data) {
        $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" /&>');
    }
    $iframe.append($form);
    $(document.body).append($iframe);
    $form[0].submit();
    $iframe.remove();
}

Spring MVC 406 status code / could not find acceptable representation

 
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
 
pom.xml
 

        <!-- Jackson JSON Processor -->

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>

 
 
For springMvc. In the XML
 
 

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="false">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=utf-8</value>
                        <value>text/xml;charset=utf-8</value>
                        <value>text/plain;</value>
                        <value>text/json;charset=utf-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

 
 
 
 
 
In the Controller
 

  @RequestMapping(value = "checkLogin", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto checkLogin(String name, String password, int role) {

        return loginService.checkLogin(name, password, role);
    }

 
 
 
——————————————————————————-
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;
    }
}

 
 

 

When to enter success and error in AJAX

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

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>

From:
http://www.cnblogs.com/zhonghua-sun/archive/2008/04/14/1152555.html

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied

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