Tag Archives: ajax

Ajax request error: provision headers are shown

Ajax always reports this error when sending a request. If you switch to another condition, the request will not report an error

Later, under the condition of error reporting, when requesting, a parameter is lost (the value of a parameter becomes undefined), which makes it impossible to enter the interface to obtain data, and then an error is reported

How to Solve Ajax Error 500 (Internal Server Error)

==========error======={"readyState":4,"responseText":"<html><head><title>Apache Tomcat/6.0.35 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 500 - </h1><HR size=\"1\" noshade=\"noshade\"><p><b>type</b> Exception report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The server encountered an internal error () that prevented it from fulfilling this request.</u></p><p><b>exception</b> <pre>org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Object is null (through reference chain: java.util.HashMap[&quot;data&quot;]-&>java.util.ArrayList[0]-&>net.sf.json.JSONObject[&quot;applyExcuse&quot;]-&>net.sf.json.JSONNull[&quot;empty&quot;]); nested exception is org.codehaus.jackson.map.JsonMappingException: Object is null (through reference chain: java.util.HashMap[&quot;data&quot;]-&>java.util.ArrayList[0]-&>net.sf.json.JSONObject[&quot;applyExcuse&quot;]-&>net.sf.json.JSONNull[&quot;empty&quot;])\n\torg.springframework.http.converter.json.MappingJacksonHttpMessageConverter.writeInternal(MappingJacksonHttpMessageConverter.java:194)\n\torg.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:179)\n\torg.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148)\n\torg.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(……

Various explanations on the Internet, but not eggs

Error reported in “codeexception.Org” in “codeexception.Org”  ”   This means that there is null in the map value

 

Null values cannot be converted to JSON when the front end is returned

Ajax defines data transfer as JSON

Solution:

1. Loop by yourself or find a tool class to handle null ”

2. Returns the front-end string. The front end is converted to JSON.

Convert to IE9 below $. Ajax to return “no transport” across domains

Programmer algorithm practice must read, common Java API skills to share>>>

$.ajax({
            type: "POST",
            async: false,
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            xhrFields: {
                withCredentials: true
            },
            url:url,
            data:data,
            success:function (response) {
                arr = response.Data.ListData;
            },
            error:function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
            }
        });

  

The

code is as above. I thought it was a problem with the code, but later, I found that IE8 does not support CORS protocol, that is, access control allow origin: * added by background config

the solution is as follows:

Add jQuery. Support. CORS = true before $. Ajax

Or, add in $. Ajax

crossDomain:true,
dataType:'jsonp',
jsonp:'callback',

Original text https://blog.csdn.net/slzll/article/details/73175971

Ajax submitting datagram in firebox_ ERROR_ DOCUMENT_ NOT_ Cached error

What are the eight life cycle hook functions of Vue>>>

Cause

In order to simulate the data returned by the interface, the group writes an automatic data filling page, which needs to be manually clicked to return every time it comes to this page. There are two forms on the page, and the target points to both_ Self, today I wrote an implementation of using JS to submit these two forms respectively. The function is very direct, and I submitted the code without thinking about it. It works in IE and chrome, but only one of the two forms is submitted in firebox. Using httpfox to capture the package, a mistake is prompted: Post (about) ns_ BINDING_ The following is a brief record of the process

Initial code:

window.onload =  autoReturn;

function autoReturn()
{
    var value = window.confirm("auto return or not?");
	if(value==true)
    {
	ajaxNotify();
	//return form
	document.return_form.submit();
    }
}

function ajaxNotify()
{
    var xmlhttp;
    if(window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
	 xmlhttp = new ActiveObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function()
    {
	 if(xmlhttp.readyState==4 && xmlhttp.status==200)
	 {
	 	console.log(xmlhttp.responseText);
	 }
    }
    //notify form
    var form = document.notify_form;
    var inputs = form.getElementsByTagName('input');
    var postData = '';
    for(var i=0, len=inputs.length; i<len; i++)
    {
        if(i!=0)
	    postData += '&';
        postData += inputs[i].name + '=' + inputs[i].value;
    }
    xmlhttp.open("POST", form.action, true);
    xmlhttp.send(postData);
    console.log("postData=" + postData);
}

The above is the original code, because the page is very simple, there is no jQuery and other plug-ins. After several times of testing in Firefox, it is found that the form submitted by Ajax post method is always unable to be submitted

POST (Aborted) NS_ BINDING_ The content in the HTTP fox request package is error loading content (NS)_ ERROR_ DOCUMENT_ NOT_ CACHED)。 I searched the Internet and found that many people met ns_ ERROR_ DOCUMENT_ NOT_ Most of the errors in cached are related to the configuration of fire cache parameters. For details, please refer to httpfox. However, this problem is not consistent with what I encountered. Under the reminder of @ Yuanbo, we use the encoding component method of JS to encode the data field once, and set the HTTP header information. The code is as follows:

After encode:

//notify form
    var form = document.notify_form;
    var inputs = form.getElementsByTagName('input');
    var postArr = [];
    for(var i=0, len=inputs.length; i<len; i++)
    {
	postArr.push(inputs[i].name + "=" + encodeURIComponent(inputs[i].value));
    }
    xmlhttp.open("POST", form.action, true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(postArr.join('&'));
    console.log("postData=" + postArr.join('&'));

However, there are still problems. No way, had to comment out the code to submit the page, only to submit the post part, even can be submitted. At this time, you will find the power of professionalism, @ Yuanbo pointed out, did firebox cancel the previous post when submitting the form?This analysis coincides with the previous error message. According to this idea, the code is further adjusted: wait for the post method to return, then submit, and set the timeout to forcibly submit the page

The final code is:

window.onload =  autoReturn;

function autoReturn()
{
    var value = window.confirm("auto return or not?");
    if(value==true)
    {
	ajaxNotify();
    }
}

function ajaxNotify()
{
    var xmlhttp;
    if(window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
	xmlhttp = new ActiveObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function()
    {
	document.return_form.submit();
	if(xmlhttp.readyState==4 && xmlhttp.status==200)
	{
	    console.log(xmlhttp.responseText);
	}
    }
    //notify form
    var form = document.notify_form;
    var inputs = form.getElementsByTagName('input');
    var postArr = [];
    for(var i=0, len=inputs.length; i<len; i++)
    {
	postArr.push(inputs[i].name + "=" + encodeURIComponent(inputs[i].value));
    }
    xmlhttp.open("POST", form.action, true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(postArr.join('&'));
    setTimeout(function(){
	document.payment_return.submit();
    }, 500);
    console.log("postData=" + postArr.join('&'));
}

Summary:

Front end code is closely related to the browser, understanding the basic principles of the browser can write more robust code

[reprint] extjs sets the timeout of Ajax request

With multi-dimensional model as the core, let the factory digital transformation and upgrading “within reach”>>>

In the Ajax requests in extjs, the default timeout of ext.ajax.request is 30 seconds. Sometimes we need to set a longer time for time-consuming operations. At this time, we need to change the timeout of ext.ajax.requse to a longer time. We can set the request timeout through ext.ajax.timeout

For example, if we have a time-consuming request that takes more than 30 seconds, we can modify the timeout by adding this statement before the code requested by ext.ajax.request

Ext.Ajax.timeout=90000;// 90 seconds

Ext.Ajax.request({
url:’xxx.php’,
params:{data; data},
success:function (response, option) {
// your business code
},
failure:function () {alert (‘communication failure ‘);}

});

The first statement in the above paragraph changes the ext.ajax.request request timeout to 90 seconds

Note: the original text is reprinted from the IT technology house of the blogger’s personal station. The original text links extjs to set the timeout time of Ajax request_ It technology house

bloggers personal technology exchange group: 960640092, WeChat blogger official account is as follows:

When parsing background JSON data with Ajax: unexpected token o in JSON at position 1

JSON data parsing exception

When doing JSON data today, the following error occurred, saying that it was an exception to parse

VM1584:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at Object.success (customer.js:170)
    at j (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at x (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

The request function is as follows:

$.ajax({
        url: "../../XXX.php",
        data: {CustomerName: $("#CustomerName").val()},
        dataType: "json",
        type: "post",
        success: function(data) {
            var jsonData = JSON.parse(data);
            alert(data[0].code);
            alert(data[0].msg);
        },
        error: function() {
            alert("error!");
        },
    });

It should be noted that when using jQuery to complete Ajax requests, there is a . between Ajax and $. You can’t leave it out here. Parsing exception is because after the end of Ajax request, the JSON data transferred in the background has been automatically converted to object type. Therefore, there is no need to use JSON. Parse manual conversion here

XMLHttpRequest status=0 (All You Should Know)

error:function(XHR,textStatus,errorThrown){
            
            if (XHR.status == 403){
                var errMsg = XHR.responseText.replace(/\"/g,"");
                swal({
                     title:errMsg,
                     text:'3 s later will closed',
                     timer:3000,
                     type:'error'
                 });
            } else {
                swal({
                    title:'Internal server error,sorry!',
                    text:'3 s later will closed',
                    timer:3000,
                    type:'error'
                });
            }

original content

In fact, this article is not only about the problem of XMLHttpRequest status = 0, but also about some problems encountered by Ajax and my reflection.

Let’s look at the whole example


<html>  
<head>  
<script type="text/javascript">  
    var xmlhttp;  
    function loadXMLDoc(url) {  
        xmlhttp = null;  
        if (window.XMLHttpRequest) {// code for all new browsers  
            xmlhttp = new XMLHttpRequest();  
        } else if (window.ActiveXObject) {// code for IE5 and IE6  
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  
        }  
  
        if (xmlhttp != null) {  
            xmlhttp.onreadystatechange = state_Change;  
            xmlhttp.open("GET", url, true);  
            xmlhttp.send(null);  
        }  
    }  
  
    function state_Change() {  
        if (xmlhttp.readyState == 4) {  
            alert(xmlhttp.status);  
            alert(xmlhttp.responseText);  
            if (xmlhttp.status == 200) {  
                alert("200");  
            } else {  
                alert(xmlhttp.status);  
                alert("Problem retrieving XML data");  
            }  
        }  
    }  
</script>  
<title>Document</title>  
<button onclick="loadXMLDoc('file:///E:/test2.html')">click</button>  
</head>  
<body>  
</body>  
</html>  


1. Why xmlhttp.onreadystatechange = state_ Change instead of xmlhttp.onreadystatechange = state_ Change();

Isn’t it written in () to call a function?Does it look for a function based on its name?After asking a few front-end teachers, they felt that they were all vague and didn’t understand the real reason. Finally, they went to consult another elder martial brother.

The purpose is to give the entire function to onreadystatechange instead of returning the last processed value of the function to onreadystatechange.

Again, I saw the XMLHttpRequest object when I reread the XML tutorial recently, and immediately linked it with Ajax.

W3C, which is used to exchange data with the server in the background, is the developer’s dream .

Today’s browsers can get objects directly through new, but ie can’t, xmlhttp = new activexobject(“ Microsoft.XMLHTTP “);

At the same time, when IE6 is running, the browser will prompt you to set ActiveX.

Onreadystatechange is an event handle. It also has onclick functions. When there is a click event, it will be processed specifically. It depends on how your function is written. Onreadystatechange is triggered by readyState, which stores the state of XMLHttpRequest

0: request not initialized
1: server connection established
2: request received
3: request processing
4: request completed and response ready

When readyState is changed, call the onreadystatechange function. Note that this function is used. Do we want to assign a function to it instead of simply returning a value.

So the problem is solved.

At the same time, it is different from:

<button onclick="dodo()">click</button>  

This is in HTML. Although it is also an event handle, its format is different. The one above is in JS code.

2. XMLHttpRequest status = 0 problem.

xmlhttp.readyState =4, all the time xmlhttp.status ! = 200。 It’s easy to output and find out xmlhttp.status=0 There is no such status code in the HTTP protocol. Finally, we find a description of XMLHttpRequest http://www.w3.org/TR/XMLHttpRequest/ .

The status attribute must return the result of running these steps:

The status value must return the result of running these steps.

1. If the state is unsent or open, return 0.
2. If the error flag is set, return 0.
3. Return the HTTP status code

If the above two situations appear before HTTP returns, 0 will appear.

Let’s talk about two buttons, one is the URL: File:///E/test2.html, the other is: http://www.baidu.com .

The first button’s URL access is only opened locally, but not through the server. You can use Wireshark to catch packets (thank you for your advice).

There is also a problem, that is xmlhttp.readyState It always changes

1: Server connection established

2: Request received

3: Request processing

4: The request has completed and the response is ready.

In this case, xmlhttp should be simulating itself, because it didn’t pass the server at all. It’s just local. Open, so the status is 0.

Although the URL access of the second button is other domain names, packet capture is available, but it is cross domain access

If the cross-origin request status is network error

This is a network error.

Although I visited it, it should be because the browser’s cross domain return header is not allowed, so the browser blocks the access control allow origin attribute.

The real way is to visit the URL in your domain name on your own server.

Run on Tomcat:

<button onclick="loadXMLDoc('http://localhost:8080/TestServlet/MyServlet')">click</button>  

Finally, I’m reflecting. I’ve been looking for the answer to the question, but when I asked some of them, I just gave them the answers that came with Baidu. Some people even ignored this question after I said that there was a mistake after adding brackets, and they could use it. But I asked a senior brother not only this answer, because this senior brother is very good at the front end, and the most important thing is that he is a technology enthusiast. He gave me the analysis of the first question, and then he went to Google to go deeper.

The gap in technology is about this. It may not be big now, but in a few years, it is estimated that it will not be a level.

The difference between people is just the same.

Finally, I would like to thank another person, who let me see the experience of a full stack engineer. The front end and the back end are connected and killed, so are the bottom layer and the business logic. A few words can connect the things I checked in the afternoon, so does the so-called real programmer. I was very excited and admired to have a talk with him. People who love technology have nothing to do with it.