Native Implementation of Ajax about the use of MIME types, the use of ajaxmime
Problem description
The following example shows the code of an Ajax post request. During the test run, the Code returns the status code 400, indicating that the server cannot understand the request and is later viewed and modified, I found that I only need to slightly modify the following code.
Original code
var send = function (url, params, fn) { var me = this; var xhr = null; var data = ''; fn = fn || function() {}; params = params || {}; for(var item in params) { data += item + '=' + params[item] + '&'; } if(data[data.length - 1] == '&') { data = data.slice(0, data.length - 1); } if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); }else if(window.ActiveXObject) { xhr= new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("post", url, true); xhr.setRequestHeader("Content-type", "application/json"); xhr.onreadystatechange = function () { if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) { fn(JSON.parse(xhr.responseText)); } }; xhr.send(JSON.stringify(params));}
Modified code
var send = function (url, params, fn) { var me = this; var xhr = null; fn = fn || function() {}; params = params || {}; if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); }else if(window.ActiveXObject) { xhr= new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("post", url, true); xhr.setRequestHeader("Content-type", "application/json"); xhr.onreadystatechange = function () { if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) { fn(JSON.parse(xhr.responseText)); } }; xhr.send(JSON.stringify(params));}
The difference between the two codes is that the modified Code removes the processing of the data variable and changes the parameter passed in send to the params variable.
Problem Solving
The problem is solved, but my questions are raised. Before using native Ajax, when the method is post, the passed parameters are in the form of "name = 123 & age = 32". Why is it possible to pass a serialized JSON object now?
At this time, I noticed the MIME type I added, that is, the Content-type field. I set "application/json", which seems to be explained, in this case, I recall that the common MIME type is "application/x-www-form-urlencoded ", in this case, the parameter passed by the send method must be like "name = 123 & age = 32". Here, the problem is solved (~ )~
Supplement
By the way, this status code 405 is the last time I saw it, when I sent a request from the front end, the parameter passed was incorrect. When I encountered it this time, this is because the backend has not added the processing of this request.
The native implementation of the above Ajax about the use of the MIME type is all the content shared by the editor. I hope to give you a reference, and hope you can also support the help house.