jQuery AJAX Character Encoding

2019-01-02 17:59发布

I'm currently coding a French website. There's a schedule page, where a link on the side can be used to load another day's schedule.

Here's the JS I'm using to do this:

    <script type="text/javascript">
    function load(y) {
        $.get(y,function(d) {
            $("#replace").html(d);
            mod();
        });
    }
    function mod() {
        $("#dates a").click(function() {
            y = $(this).attr("href");
            load(y);
            return false;
        });
    }
    mod();
    </script>

The actual AJAX works like a charm. My problem lies with the response to the request.

Because it is a French website, there are many accented letters. I'm using the ISO-8859-15 charset for that very reason. However, in the response to my AJAX request, the accents are becoming ?'s because the character encoding seems to be changed back to UTF-8.

How do I avoid this? I've already tried adding some PHP at the top of the requested documents to set the character set:

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

But that doesn't seem to work either. Any thoughts?

Also, while any of you are looking here...why does the rightmost column seem to become smaller when a new page is loaded, causing the table to distort and each <li> within the <td> to wrap to the next line?

Cheers

22条回答
心情的温度
2楼-- · 2019-01-02 17:59

I tried many suggestions to read in a textfile with German special characters (ä,ö,ü). In the end:

 $.ajax({
        async:false,
        type: "GET",
        url: "data/FileName.txt",
        dataType: "text",
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        success: function (data) {
           alert(data);
        }
    });

let me read in the special characters, but only AFTER I explicitly saved FileName.txt in the UTF-8 format. The standard format for saving text files in the Windows Editor is ANSI and not UTF-8, but it can be changed if you "Save as" and use the dropbox next to the Save-Button or use a better Editor to start with.

查看更多
余生无你
3楼-- · 2019-01-02 18:01

I´ve had the same problem with pages that:

  • Show up fine when called normally
  • Have the special characters messed up when called via an ajax request

To solve the problem (using php), I used utf8_encode() or htmlentities() on the source data. Both worked, I have used them in different projects.

查看更多
步步皆殇っ
4楼-- · 2019-01-02 18:02

I had similar problem. I have text file with json data that has French text. There was always issue displaying some characters. In my case, JavaScript program uses Ajax to retrieve the json text file as follows:

$.ajax({
    async: false,
    type: 'GET',
    url: 'some-url',
    success: function(data, status) {
        mainController.constructionStageMaster = data.records;
     }
});

The returned data always had incorrect accented French letters.

The json text looks as follows:

{
    "records": [
        {
            "StageDesc": "Excavation, Fondation et Bases",
            "Allowed": 9,
            "Completed": 0,
            "TotalCompleted": ""
        },
        {
            "StageDesc": "Étanchement et Remblayage",
            "Allowed": 3,
            "Completed": 0,
            "TotalCompleted": ""
        },
        {
            "StageDesc": "Encadrement et revêtement mural intermédiaire",
            "StageDesc_fr": "Encadrement et revêtement mural intermédiaire np++",
            "StageDesc_fr2": "Encadrement et revêtement mural intermédiaire",
            "Allowed": 15,
            "Completed": 0,
            "TotalCompleted": ""
        }
        ...
    ]
}

Note in the above sample data, the 3rd element, I placed the text with the correct é and incorrect ê French accented letters.

For your information, it seemed that there is some global configuration of Eclipse project using ISO-8859-1 character encoding. In your case it might be different encoding.

After checking the solutions above and playing around with the the project, this is what solved my problem:

  • Find the source of the text which has the correct display of the French text
  • Copy the text
  • Goto Eclipse, open the text file which has the data
  • Right-click the file in the explorer, open properties, and change the encoding to ISO-8859-1
  • Fix the text so that it is displayed properly. Use copy/paste or the keyboard
  • You may have to use the keyboard arrow keys (left/right) to make sure there are no hidden culprit letters that will show-up on HTML with a funny shape. Delete such hidden letter
  • Save the file

Now, in my case, I didn't specify any encoding options in the Ajax call and it works fine. Also, if I change the encoding of the text file with json data, it would still work fine.

Tarek

查看更多
情到深处是孤独
5楼-- · 2019-01-02 18:07

I have faced same problem and tried several ways. And i found the solution. If you set request header for "Accept" like below;

$.ajax({
        data: parameters,
        type: "POST",
        url: ajax_url,
        dataType: 'json',
        beforeSend : function(xhr) {
            xhr.setRequestHeader('Accept', "text/html; charset=utf-8");
        },
        success: callback
});

you will see that all the characters seems correct

查看更多
像晚风撩人
6楼-- · 2019-01-02 18:09

I have been fiddling around with this problem and found out that this solution works for Firefox and safari (yes, im on a mac at the moment).

when getting the request, i made a content-type=iso-8859-1 here:

if (window.XMLHttpRequest) { // Mozilla, Safari, ...
  httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType) {
            httpRequest.overrideMimeType('text/xml; charset=ISO-8859-1');
        }
    }

Please tell me if someone finds out this doesn't work in ie.

查看更多
梦寄多情
7楼-- · 2019-01-02 18:12

If the whole application is using ISO-8859-1, you can modify your jquery.js replacing all occurences of encodeURIComponent by escape (there are 2 occurrences to replace in the current jquery script - 1.5.1)

See encodeUIComponent and escape for more information

查看更多
登录 后发表回答