【问题标题】:How to set the Content-Type header using JavaScript如何使用 JavaScript 设置 Content-Type 标头
【发布时间】:2011-01-04 18:04:33
【问题描述】:

如何使用 JavaScript 将 Content-Type 标头设置为“application/x-www-form-urlencoded; charset=UTF-8”?

我需要这样做,这样我才能查看带有法语字符的表单而不会产生错误。

谢谢

【问题讨论】:

  • 为什么需要JS?你应该在服务器端做这个。
  • 您遇到了什么错误?为什么需要使用 JavaScript?
  • 如果没有人理解,你应该澄清这个问题,或者接受一个答案。

标签: javascript utf-8 header set content-type


【解决方案1】:
【解决方案2】:

内容类型由服务器在将 HTML 发送到浏览器之前设置。你不能用 JavaScript 修改它。

【讨论】:

    【解决方案3】:

    您可以在页面的head 中添加meta 标签,或者在服务器端发送header。

    例子,

    <meta http-equiv="Content-type" content="application/x-www-form-urlencoded; charset=UTF-8"/>

    在服务器端,比如 PHP:

    <?php
      header( 'Content-type: application/x-www-form-urlencoded; charset=UTF-8' );
    ?>
    

    就是这样!

    【讨论】:

      【解决方案4】:

      我假设您想与服务器通信,例如提交表单,然后服务器将结果发回给您,您需要在其中正确的Content-type 才能允许服务器通信。

      如果是这样,那么XMLHttpRequest.setRequestHeader() 可能会有所帮助。


      一个例子

      (
        () => {
          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);
        }
      )()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-22
        • 2013-12-10
        • 2015-05-05
        • 2011-01-26
        • 2019-04-19
        • 1970-01-01
        • 2012-05-27
        相关资源
        最近更新 更多