Tag Archives: ajax

Jquery use queue to implement Ajax request queue Simple Example

Packaging method

var axmq = {
    queues: [],
    //network request
    request: null,
    //Execution queue
    render: function() {
    //append queue
    append: function(func) {
    //clear queue
    clear: function() {
        if (0 === $(document).queue().length) {
            axmq.queues = [];
    //POST request
    post: function(args) {
        var params = {
            url: 'https://www.sample.com/api',
            headers: {},
            data: {},
            buffer: function() {},
            callback: function() {}
        $.extend(params, args);
        var headers = {
            Accept: 'application/json;charset=utf-8'
        if (Object.keys(params.headers).length > 0) {
            $.extend(headers, params.headers);
        if (axmq.request == null) {
            axmq.request = $.ajax({
                async: true,
                type: 'POST',
                url: params.url,
                headers: headers,
                data: params.data,
                dataType: 'JSON',
                beforeSend: function() {
                success: function(res) {
                    axmq.request = null;
                error: function(err) {
                    axmq.request = null;
                        errcode: 5001,
                        errmsg: 'System busy'
    sample: function() {
        axmq.append(function() {
                url: 'https://www.sample.com/api/a'
        axmq.append(function() {
                url: 'https://www.sample.com/api/b'
        axmq.append(function() {
                url: 'https://www.sample.com/api/c'

Call example


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

To record, the Ajax request is as follows:

		let xhr = new XMLHttpRequest();
        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);
			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.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);
                 else {
          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

[Solved] it only responds to error and does not enter success after AJAX is successfully processed

1. Problem description

Front end request code

    url: 'getOne', 	
    data: {		
        name: 'zhangsan',
        pwd: '123'
    type: 'get',		
    dataType: 'json',	
    success: function (res) { 
        alert("成功" + res)
    error: function (xhr, errorMessage, e) { 
        alert("失败" + errorMessage);

Backend servlet code

@WebServlet(name = "getOne", urlPatterns = "/getOne")
public class GetOne extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      	// Set encoding
       // Processing business logic
         // Responding to the request, there may be IO exceptions in the way of using the stream, so the exception is caught
        PrintWriter out = response.getWriter();
        try {
            out.write("ajax request successful");
        } catch (Exception exception) {

Then it is found that after each processing, it will only respond to the abnormal error function and cannot enter success

2. Problem solving

The code above looks OK at first glance. I thought so at first. However, after some analysis, it is found that the format of the return value type at the back end is incorrect

What do you mean?

I set the JSON format in the back-end response


However, I output the ordinary string with the stream when responding, not the JSON format string

out.write("ajax request successful");

How to solve it?

Method 1: change the string format to JSON format
back end output: out.Write ("{'data':'ajax request succeeded '}")
front end: alert ("success" + res.data) method 2: change the type of request and processing to text
back end: response.setcontenttype ("application/JSON; charset = UTF-8")
front end: datatype: 'text'

An error is reported when passing data pages using Ajax: Vue is not defined

1、 Resolution:

Literal meaning: Vue is not defined, that is, the introduction of Vue source code;

2、 Try to resolve:

1: Try 1: check whether the Vue source code import (path and script tag) is wrong
2: try 2: there is no problem with the import syntax, that is, check whether there is a Vue source code file in the target folder, and find no (reason: I added the Vue source code file manually later, but it was not generated in time in the target)

3、 Solution steps:

Click clean to clean and regenerate the target file. The Vue source code is successfully introduced and the error is resolved;


There was an unexpected error (type=Method Not Allowed, status=405). Request

When using Ajax to submit a page, the above exception is thrown, and the final result is found

<form id="newsForm" method="post" enctype="multipart/form-data">
        News title:<input name="ntittle"><br>
        News summary:<input name="nsummary"><br>
        News content:<input name="ncontent"><br>
        News by:<input name="nauthor"><br>
        Post Time:<input name="ndate" ><br>
        Image:<input type="file" name="newpic"><br>
        News topics:<select name="newsType.ntypeId">
            <option value="-1">Please select news topic</option>
       <input type="hidden" name="nid"><br>
        <input type="hidden" name="npic"><br>
        <input type="submit" value="ADD">

AJAX is used, so the submission is not a direct submission, so you should use button and serialize the form.

<input type="button" value="ADD">

Echarts Partially introduced error: TypeError: Cannot read property ‘findAxisModel’ of undefined

When introducing dependencies locally in echarts, if there are dependencies that need to be used, an error will be reported if they are not introduced. For example, when using histogram + polar coordinates to display a ring chart, if Ploar is not introduced, an error will be reported in the title. At this time, just introduce this dependency:


Error message caused by browser plug-in

1. Error description

DevTools failed to load SourceMap: Could not load content for 
HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME
Unchecked runtime.lastError: The message port closed before a response was received.

2. Cause analysis

It is mainly caused by the use of plug-ins such as oil monkey or Xunlei in Google browser

3. Solutions

Address bar entry chrome://extensions/ , turn off the oil monkey or thunder one by one, if not, F12 – & gt; Settings – & gt; Perferences–> Sources, disable JavaScript maps and CSS maps, clear cache and re access

Interface request error 504 gateway time out [How to Solve]

This article mainly introduces the solution of page 504 gateway time-out

1. 504 gateway time out reason?

Because of the browser access interface request, the default timeout event is 1 minute. When the 504 interface timeout is encountered, first we need to see whether the Ajax interface request is set   Timeout. Next, check whether nginx has set the agent timeout.

2. Inspection procedure

1. Front end Ajax settings

  url: '',
  type: 'post',
  data: postData,
  timeout: 1000*60*10,
  success: function(data){

2. Nginx agent timeout setting

proxy_connect_timeout    600;
proxy_read_timeout       600;
proxy_send_timeout       600;
proxy_buffering    off;
proxy_buffer_size  128k;
proxy_buffers 100  128k;

3、 Problem extension (native JS encapsulates Ajax requests)

At that time, the Ajax request of jQuery was used, and the datatype: JSON was uniformly defined by the interface. Due to the file flow returned by the interface, the successful callback was not triggered and did not want to modify the datatype. Therefore, the Ajax request was encapsulated with native JS.

    var timeoutFlag=null;
    var xhr=new XMLHttpRequest();
    var url=""//request path, get request can spell the parameters into the address
    xhr.open(type,url,async);//type request type url address async whether asynchronous request 
    xhr.responseType='blob';//If the return data is a file stream, you can set it to blob type
    xhr.timeout=1000*60*60;//timeout time This is set to one hour
    xhr.setRequestHeader('token',token);//set header token
            if(xhr.status==200 || xhr.status==304){


[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.

                    success:function (data) {
                    //    data is the server-side response data