Ajax learning notes, native Ajax, jQuery Ajax, cross domain problems

Keywords: Javascript Front-end JQuery Ajax

Ajax learning notes

AJAX is a developer's dream because you can:

  • Update web pages without refreshing pages
  • Request data from the server after the page is loaded
  • Receive data from the server after the page is loaded
  • Send data to the server in the background

1. Native js implements ajax

<script>
    var box = $(".box");
    $("button").click(function () {
        // Creating ajax objects
        var xhr = new XMLHttpRequest();
        // Set the type of response body, and the result of json string will be automatically converted into js object
        xhr.responseType = "json";
        /*
           The first parameter of this method is the type of access, and the second parameter is the url of the request
           Initialization, you can add parameters after the url
         */
        xhr.open("Get","http://localhost/ssm/test");
        // Set request header
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        // Send the request. If the request mode is post, set the request parameters in the send() method
        // xhr.send("a=100&b=200");
        xhr.send();

        // Set request timeout, 2s
        xhr.timeout = 2000;
        // Callback function when the request times out
        xhr.ontimeout = function () {
            alert("request timeout!");
        };
        // Callback function in case of network exception
        xhr.onerror = function () {
          alert("Your network is abnormal!");
        };
        // Set cancel request
        // xhr.abort();

        // Get the response. When xhr.readyState is 4, the server will complete the response
        xhr.onreadystatechange = function () {
            if(xhr.readyState === 4){
                // The status code that starts with 2 is the successful response
                if(xhr.status >= 200 && xhr.status < 300){
                    box.html(xhr.response.userName);
                }
            }
        };
    });
</script>

2. jQuery implements ajax

get() method:
Request through get request.

$(function () {
    // The first method, $. get(), requests through the method
    var box = $(".box");
    $("button").click(function () {
        $.get("http://localhost/ssm/test",{
            a : 100,
            b : 200
        },function (data) {
            // Callback function to execute when the request succeeds
            console.log(data);
            box.html(data.userName);
        },"json");
    });
});

Four parameters:

  • url: the requested address.
  • data: parameter, passed in the form of {key:value}, and multiple values are separated by commas.
  • function(data) {}: the callback function when the request is successful. The returned data is encapsulated in data and passed in as a parameter.
  • Returned data type: set the returned data type and pass it in as a string. If it is json, the data of the json string will be automatically converted into js objects.

The first parameter of the method is required, and the next three parameters are optional values. The callback function can be called when the method request is successful. If you need to execute a function when an error occurs, use $. ajax, a callback function without an error.

getJSON():

// The second method $. getJSON()
$("button").click(function () {
    $.getJSON("http://localhost/ssm/test",
        {
            a : 100,
            b : 200
        },
        function (data) {
            console.log(data);
            box.html(data.userName);
        }
    );
});

This method is similar to the get() method, except that the returned json string is automatically converted into a js object without specifying the returned data type. In this way, the cross domain problem is solved at the same time.

post():
Request through post request.

// The third method $. post()
$("button").click(function () {
    $.post("http://localhost:80/ssm/test1",
        {
            a : 100,
            b : 200
        },
        function (data) {
            console.log(data);
            box.html(data.userName);
        },"json");
});

The parameter is similar to the request of the get() method.

ajax():

$("button").click(function () {
    $.ajax(
        {
            type: "get",   // Type of request
            url: "http://localhost/ssm/test ", / / requested address
            data: "a=100&b=200",  // Requested parameters
            dataType: "json",  // Type of returned data
            timeout: 2000,  // Timeout, 2s
            success: function (data) {  // Callback function when the request is successful
                console.log(data);
                box.html(data.userName);
            },
            error: function () {  // Callback function for request failure
                console.log("Your request does not exist!");
            }
        }
    );
});

Parameters are usually passed in as an object in this way. Type indicates the type of access, url indicates the path of the request, data indicates the parameter, success indicates the callback function when the request is successful, and the data returned from the back end will be encapsulated in data. dataType indicates setting the return data type, and json converts the returned json string into a js object.

load():
Load the remote HTML file code and insert it into the DOM.

$("button").click(function () {
    // Load the remotely requested data into the specified element, which can be an element in the data
    // It is usually used to refresh a part of a page and give a selector of elements in a page after the request address
    box.load("http://localhost/ssm/index.html #content");
});

3. Cross domain problem

Generally, cross domain problems are solved by back-end programmers, and the front-end can also be solved, but it is inconvenient. Here are several solutions to cross domain problems.

  1. jsonp is used to solve cross domain requests at the front end, but this method only supports get requests and is not recommended.
  2. Set the response header. Set a response header at the back end to support cross domain requests in a fixed format.
response.setHeader("Access-Control-Allow-Origin","*");
  1. To solve the cross domain problem in spring MVC, you can add an annotation @ CrossOrigin on the controller's request, which can also solve the cross domain problem.
@RequestMapping(value = "/test",method = RequestMethod.GET)
@ResponseBody
@CrossOrigin
public String test(HttpServletResponse response){
    // Set response headers to solve cross domain problems
    response.setHeader("Access-Control-Allow-Origin","*");
    User user = new User(1, "Zhang San", "123");
    return JSON.toJSONString(user);
}
  1. Setting a filter will require cross domain requests to be intercepted and filtered.
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component
public class CrossFilter implements Filter {
    private static Logger logger = LoggerFactory.getLogger(CrossFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
      	// Set request cross domain
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        httpServletRequest.getSession();
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Content-type", "application/json");
        httpResponse.setHeader("Cache-Control", "no-cache, must-revalidate");
        chain.doFilter(request, httpResponse);
    }
}

Posted by jeny on Sun, 31 Oct 2021 18:57:13 -0700