How to change ajax-charset?

前端 未结 4 1993
鱼传尺愫
鱼传尺愫 2020-12-03 11:09

How can I change the default encoding used by $.post()?

The arguments are encoded with UTF-8. How can I encode it with ISO 8859-1?

相关标签:
4条回答
  • 2020-12-03 11:45

    You could use:

    contentType:"application/x-javascript; charset:ISO-8859-1"
    
    0 讨论(0)
  • 2020-12-03 11:47

    By giving the content type explicitly during ajax call as below may allow you to override the default content type.

    $.ajax({
            data: parameters,
            type: "POST",
            url: ajax_url,
            timeout: 20000,
            contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
            dataType: 'json',
            success: callback
    });
    

    You would also have to specify the charset on the server.

    Ex: for php

    <?php header('Content-Type: text/html; charset=ISO-8859-15'); ?>
    

    I hope this may help you.

    0 讨论(0)
  • 2020-12-03 11:53

    It seems the charset cannot be changed anymore – $.ajax docs states:

    The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.

    0 讨论(0)
  • 2020-12-03 12:02

    See section 4.5.6.4.4.3 of the XHR spec: https://xhr.spec.whatwg.org/#the-send()-method

    If contentTypeRecord is not failure, contentTypeRecord’s parameters["charset"] exists, and parameters["charset"] is not an ASCII case-insensitive match for "UTF-8", then:

    Set contentTypeRecord’s parameters["charset"] to "UTF-8".

    The spec forces browsers to always send as UTF-8.

    You may however, use the fetch API. Since it's not an XHR, posting using fetch will honour your encoding.

    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': `text/plain; charset=${yourCustomEncoding}`
      },
      body
    }).then(...
    
    0 讨论(0)
提交回复
热议问题