Tag Archives: JQuery

Jquery use queue to implement Ajax request queue Simple Example

Packaging method

var axmq = {
    //Queues
    queues: [],
    //network request
    request: null,
    //Execution queue
    render: function() {
        $(document).queue(axmq.queues);
    },
    //append queue
    append: function(func) {
        axmq.queues.push(func);
    },
    //clear queue
    clear: function() {
        $(document).dequeue();
        if (0 === $(document).queue().length) {
            axmq.queues = [];
            $(document).clearQueue();
        }
    },
    //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() {
                    params.buffer();
                },
                success: function(res) {
                    console.log(res);
                    axmq.request = null;
                    axmq.clear();
                    params.callback(res);
                },
                error: function(err) {
                    console.log(err);
                    axmq.request = null;
                    axmq.clear();
                    params.callback({
                        errcode: 5001,
                        errmsg: 'System busy'
                    });
                }
            });
        }
    },
    //example
    sample: function() {
        axmq.append(function() {
            axmq.post({
                url: 'https://www.sample.com/api/a'
            });
        });
        axmq.append(function() {
            axmq.post({
                url: 'https://www.sample.com/api/b'
            });
        });
        axmq.append(function() {
            axmq.post({
                url: 'https://www.sample.com/api/c'
            });
        });
        axmq.render();
    }
};

Call example

axmq.sample();

[Solved] Uncaught Error: Highcharts error #16

Highcharts error #16 is due to duplicate Highcharts definitions. The reason for this error is that the namespace of Highcharts is duplicated.

The namespace of Highcharts actually exists in the Highcharts.js file that we refer to when we use Highcharts.

Solution
Remove the Highcharts.js from the nested subpages and leave only the reference to the main page, and the error will not be reported.

Conclusion
Referencing Highcharts.js on the main page and referencing Highcharts.js on the sub-page nested in it will cause duplicate Highcharts definitions whenever the sub-page is loaded.

[Solved] Jquery addclass reports an error under Firefox

There is no problem with the following code in Google browser and an error is reported in Firefox:

const doms = document.getElementsByClassName("cesium-baseLayerPicker-dropDown")
        for (let i in doms) {
            const dom = doms[i]
            if (dom) {
                $(dom).addClass("scroll-1")
            }
        }

The following modifications are required

 $(".cesium-baseLayerPicker-dropDown").addClass("scroll-1")

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

1. Problem description

Front end request code

$.ajax({
    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
       response.setContentType("application/json;charset=utf-8");
       // 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");
            out.close
        } catch (Exception exception) {
            out.write(exception);
        }
        out.close();
    }
}

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

response.setContentType("application/json;charset=utf-8");

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'

Error message for HLS Video Fusion for the second time when using mars3d

Using Mars technology’s mars3d API and several video fusion written according to the sample code, clicking different web page tags will fly to different locations and turn on Video Fusion there.

    var video3D = new mars3d.graphic.Video3D({
        // type: mars3d.graphic.Video3D.Type.Image,
        // url: videoInfo.pic_url,
        type: mars3d.graphic.Video3D.Type.Video,
        dom: $("#trailer"),
        position: videoInfo.position,
        cameraPosition: videoInfo.cameraPosition,
        style: videoInfo.style,
        showFrustum: videoInfo.showFrustum,
    });
     gLayer.addGraphic(video3D);
    map.setCameraView(videoInfo.view);

However, glayer. Addgraphic (video3d) often appears; report errors. The first call is sure to succeed, and then the second call may fail. After a failure, all methods fail, which will also prevent the call of other methods, such as flight. Error message: unable to:_ 0xc3d9ee add addeventlistener.

After debugging, I found that this DOM element was obtained for the first time

the second time, it was just (forgot the screenshot):

dom:{
	selector:#trailer
}

Therefore, the specific reason for the problem is not clear, but it must be related to jQuery. The second time, I don’t know why I didn’t get the DOM elements completely and then pass them in
No, jQuery is fine anyway:

    var video3D = new mars3d.graphic.Video3D({
        // type: mars3d.graphic.Video3D.Type.Image,
        // url: videoInfo.pic_url,
        type: mars3d.graphic.Video3D.Type.Video,
        dom: document.getElementById("trailer"),
        position: videoInfo.position,
        cameraPosition: videoInfo.cameraPosition,
        style: videoInfo.style,
        showFrustum: videoInfo.showFrustum,
    });
     gLayer.addGraphic(video3D);
    map.setCameraView(videoInfo.view);

ERROR Invalid options in vue.config.js: “plugins“ is not allowed

Problem Description:

When importing jQuery, if index. JS is not found, it is directly added to Vue. Config. JS , and the following error occurs

Reason: unknown

resolvent:

Add configurewebpack to the outer layer

const path = require('path')

var webpack = require('webpack')


function resolve(dir) {
    return path.join(__dirname, dir)
}
module.exports = {
    configureWebpack: {
        plugins: [
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery",
                "windows.jQuery": "jquery"
            })
        ]
    }
}

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

$.ajax({
  url: '',
  type: 'post',
  data: postData,
  timeout: 1000*60*10,
  success: function(data){
    console.log(data)
  },
  complete:function(XHR,TextStatus){
    if(TextStatus=='timeout'){ 
      console.log("Timeout");
    }
  }
})

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.

getAjax(url,callback){
    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
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            window.clearTimeout(timeoutFlag);
            if(xhr.status==200 || xhr.status==304){
                callback(xhr.response);
            }
        }
    }
    xhr.send(data);
    timeoutFlag=window.setTimeout(function(){
        window.clearTimeout(timeoutFlag);
        xhr.abort();
    },xhr.timeout);
}
getAjax('URL',function(res){
})

 

[Solved] jQuery Error: Uncaught TypeError: this.attr is not a function

$(".answer").on("click", function () {
  console.log(this) 
  console.log(this.attr("class")) //error this.attr is not a function
});

JQ calls the method with JQ object. Method name (xxx)

$(".answer").on("click", function () {
  console.log($(this)) 
  console.log($(this).attr("class")) 
});

If the callback function is of the following form

()=>{
....
}

It should be written as

$(".answer").on("click", (el)=>{
  console.log($(el.target)) 
  console.log($(el.target).attr("class")) 
});

Note: DOM object obj is converted to JQ object — & gt$( obj)

@requestbody: How to Use or Not Use

First of all, note that @ requestbody accepts the JSON string
so write this

dataType:"json",
contentType: 'application/json',
data: JSON.stringify(data.field),

Instead of @ requestbody, you can directly receive the JSON type

dataType:"json",
data: data.field,

The situation of not using @ requestbody
front end page

$.ajax({
		url: "http://localhost:8081/role//saveOrUpdate",
		method:"post",
	   dataType:"json",     
			// contentType: 'application/json',
		data: data.field,   
		success(data){
			console.log("======================")
				console.log(data.field)
			if(data.code == 200){
			layer.msg('add success', function () {
			 window.location = 'list.html';
				}); 
				}
		},
error(data){
	console.log(data)
	if(data.code != 200){
layer.msg(data); 
								}
								}
							});

Back end:

@PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(Roles roles){
        System.out.println(roles);
        boolean saveOrUpdate = roleService.saveOrUpdate(roles);
        if(saveOrUpdate == true)
            return Result.succ(null);
        else
            return Result.fail("failed to add");
    }

Using @ requestbody
front end:

$.ajax({
								url: "http://localhost:8081/role//saveOrUpdate",
								method:"post",
								dataType:"json",
								contentType: 'application/json',   
								data: JSON.stringify(data.field),  
								success(data){
									console.log("======================")
									console.log(data.field)
									if(data.code == 200){
										layer.msg('add success', function () {
										    window.location = 'list.html';
										}); 
									}
								},
								error(data){
									console.log(data)
									if(data.code != 200){
										layer.msg(data); 
								}
								}
							});

back-end

@PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Roles roles){
        System.out.println(roles);
        boolean saveOrUpdate = roleService.saveOrUpdate(roles);
        if(saveOrUpdate == true)
            return Result.succ(null);
        else
            return Result.fail("failed to add");
    }