Tag Archives: ajax

[Solved] Cannot read properties of undefined (reading ‘ajax‘); Cannot read property ‘ajax‘ of undefined

Cannot read properties of undefined (reading ‘ajax‘); Cannot read property ‘ajax‘ of undefined

Sending requests using ajax in jQuery. it report an error: Cannot read properties of undefined (reading 'ajax'); Cannot read property 'ajax' of undefined

Codes that report an error:

            $.ajax({
                type:"POST",
                url:"pageServlet",
                data:jsonData,
                dataType:"json",
                success:function (data) {
                    alert(data);
                }
            })

Solution: Change $ to jQuery

            jQuery.ajax({
                type:"POST",
                url:"pageServlet",
                data:jsonData,
                dataType:"json",
                success:function (data) {
                    alert(data);
                }
            })

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] ajax Error: Uncaught SyntaxError: Unexpected end of JSON input

To record, the Ajax request is as follows:

		let xhr = new XMLHttpRequest();
        xhr.open("get","https://music.kele8.cn/search");
        xhr.send();
       
        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);
                console.log(ans);
            }
			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.send();
                        
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);
                         console.log(res);
                 }
                 else {
                        console.log(arr);
                }
          }
          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

$.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'

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;

Screenshot:

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>
        </select><br>
       <input type="hidden" name="nid"><br>
        <input type="hidden" name="npic"><br>
        <input type="submit" value="ADD">
    </form>

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:

require("echarts/lib/component/polar")

Error message caused by browser plug-in

1. Error description

DevTools failed to load SourceMap: Could not load content for 
chrome-extension://ncennffkjdiamlpmcbajkmaiiiddgioo/js/xl-content.js.map: 
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

$.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){
})