How to set the Content-Type header using JavaScript
How can you set the Content-Type header to "application/x-www-form-urlenco开发者_如何学编程ded; charset=UTF-8" using JavaScript?
I need to do this so I can view a form with french characters without generating errors.
Thanks
Headers are set by the server delivering the content-type as part of the HTTP message. By the time it's in the browser and running the javascript it's too late. Do you have access to the server-side code? Why not set the content type to utf-8 in there? You can also do it as part of the meta tag in the head.
You can add a meta
tag into the head
of the page, or send the header server-side.
example,
<meta http-equiv="Content-type" content="application/x-www-form-urlencoded; charset=UTF-8"/>
on the server-side, say PHP:
<?php
header( 'Content-type: application/x-www-form-urlencoded; charset=UTF-8' );
?>
that's it!
The content type is set by the server before it sends the HTML to the browser. You can't modify it with JavaScript.
I assume that you want to communicate with the server, for example, to submit a form, and then the server sends you back the results, in which you need the correct Content-type
to allow the server to communicate.
if so, then XMLHttpRequest.setRequestHeader() may help.
an example
(
() => {
const form = document.forms.namedItem("my-query-form")
form.addEventListener('submit', function (submitEvent) {
const outputElement = document.getElementById("msg")
const xhr = new XMLHttpRequest();
xhr.open("POST", "query", true);
xhr.setRequestHeader("Content-Type", "application/json"); // <----
xhr.onload = function (oEvent) {
if (xhr.status === 200) {
outputElement.innerHTML = `<p style="color:green;">${xhr.responseText}</p>`;
setTimeout(function () {
window.location.href = "/home";
}, 1000);
} else {
outputElement.innerHTML = `<p style="color:red;">Error ${xhr.status}: ${xhr.responseText}</p>`
}
};
const htmlFormControlsCollection = submitEvent.target.elements
const jsonData = JSON.stringify(
{
"username": htmlFormControlsCollection["username"].value,
});
xhr.send(jsonData);
submitEvent.preventDefault();
}, false);
}
)()
精彩评论