developer tip

jQuery AJAX 문자 인코딩

copycodes 2020. 12. 14. 20:03
반응형

jQuery AJAX 문자 인코딩


현재 프랑스 웹 사이트를 코딩하고 있습니다. 옆에있는 링크를 사용하여 다른 날의 일정을로드 할 수있는 일정 페이지가 있습니다.

이 작업을 수행하는 데 사용하는 JS는 다음과 같습니다.

    <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>

실제 AJAX는 매력처럼 작동합니다. 내 문제는 요청에 대한 응답에 있습니다.

프랑스어 웹 사이트이기 때문에 악센트가있는 글자가 많이 있습니다. 바로 그 이유로 ISO-8859-15 문자 세트를 사용하고 있습니다. 그러나 내 AJAX 요청에 대한 응답에서 문자 인코딩이 UTF-8로 다시 변경되는 것처럼 보이기 때문에 악센트가?가됩니다.

이것을 어떻게 피할 수 있습니까? 문자 집합을 설정하기 위해 요청 된 문서의 맨 위에 PHP를 추가하려고 이미 시도했습니다.

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

그러나 그것도 작동하지 않는 것 같습니다. 이견있는 사람?

당신의 여기에서 찾고있는 동안 또 ... 왜 오른쪽 열에는 새 페이지가로드 될 때 테이블을 왜곡하는 원인이 작아 보인다 않고, 각 <li>내에는 <td>다음 행으로 포장?

건배


UTF-8은 모든 악센트와 외래 문자를 처리해야합니다. 데이터 소스에서 사용하지 않는 이유는 무엇입니까?

편집
[ 테스트 파일의 아카이브 사본. ] 데이터와 함께

처음에는 모든 것이 UTF-8이어야합니다. 메모장 ++에 파일을로드하고 utf-8로 변환하고 문자를 액센트로 수동으로 변경해야했습니다. 일단 완료되면 모든 것이 매력처럼 작동합니다.

BTW, 서버가 php-process .html 파일로 정의되어 있지 않으면 ajax로로드하는 파일이 iso 문자 세트를 얻지 못합니다. iso charset 사용을 고집하는 경우 html 파일 대신 php 파일을 요청하고 파일 자체가 아닌 헤더에 문자 집합을 정의하십시오.


AJAX 호출에서 콘텐츠 유형을 지정하면 노르웨이 사이트에서 내 문제가 해결되었습니다.

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

또한 서버에서 문자 집합을 지정해야합니다.

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

$str=iconv("windows-1250","UTF-8",$str);

결국 나를 도왔던


ISO-8859-15를 문자 인코딩으로 사용하도록 서버를 설정해야합니다 (적절한 HTTP 헤더 추가). html 본문에서하는 것은 도움이되지 않습니다.

이 선을 볼 수 있습니다

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

귀하의 html 소스에서. 이것은 일어나지 않아야합니다. 라이브 HTTP 헤더를 사용하여 적절한 charset HTTP 헤더를 볼 수 없습니다. 첫 페이지와 ajax 서비스 모두에 사용하십시오.


나는 javascript escape () 메소드의 사용을 강력하게 제안합니다.

다음과 같이 양식 값을 잡아 jQuery와 함께 사용할 수 있습니다.

var encodedString = escape($("#myFormFieldID").val());

내 PHP 응용 프로그램의 경우 솔루션에는 각 변수에 대한 utf8_decode 함수가 포함되었습니다 $_POST.

예 : (서버 측)

if( strtoupper($_SERVER['REQUEST_METHOD']) == "POST" ){
$variable = htmlentities($_POST['variable']); // wrong
$variable = htmlentities( utf8_decode($_POST['variable']) ); // right
}

Abraços !!! (안녕!!!)


ajax 파일의 변수를 인쇄 할 때. 넣어

htmlentities()

주변에서 작동하는지 확인하십시오. 아이슬란드 아약스 애플리케이션에서 저를 위해 일했습니다.


스페인어 포털의 콘텐츠 댓글 시스템에서 작업하면서 비슷한 문제가 발생했습니다. 마침내 내 문제를 해결 한 것은 jQuery 문자 집합을 엉망으로 만드는 대신 여러 시간 동안 검색 한 후 처리 한 PHP에서 utf-8에서 ISO-8859-1로 다시 디코딩하는 것이 었습니다. 아약스 POST. PHP에는 내장 함수 utf8_decode()가 있으므로 주석 문자열로 가장 먼저 수행하는 작업은 다음과 같습니다.

$comentario = utf8_decode($_POST['comentario']);

(그리고 내가 사용 nl2br()하고 htmlentities()HTML과 PHP 함수가 텍스트를 준비하기 위해 저장되는 대신 특수 문자의 실체)

행운과 평화가 온통! 세바


나는이 문제를 다루고 있었고이 솔루션이 Firefox 및 safari에서 작동한다는 것을 알았습니다 (예, 현재 Mac에서 im).

요청을받을 때 여기에 content-type = iso-8859-1을 만들었습니다.

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

누군가 이것이 ie에서 작동하지 않는다는 것을 알게되면 알려주십시오.


다음을 지정 했음에도 불구하고 스웨덴 / 노르웨이 문자가 물음표로 나타나는 문제가있었습니다.

contentType: "application/json; charset=utf-8",

이것은 encodeURIComponent문자열 에 추가 하여 해결되었습니다 .

url: "/set_comment.do?text=" + encodeURIComponent(comment),

내 페이지에서 ASP와 비슷한 문제가 발생했습니다. 나는 그렇게 해결했다 :

1) Jquery ajax 메서드에 의해 호출되는 ASP 파일의 시작 부분에 다음과 같은 명령을 삽입합니다.

Response.Charset = "windows-1252"

내 asp 페이지에서 charset이 정의되지 않았고 ANSI 인코딩으로 파일을 저장했습니다 (텍스트 편집기를 메모장 ++로 사용).

2) jquery ajax 메서드를 사용하여 ASP 파일을 호출하는 html 파일에서 아래에 표시된 매개 변수 내용 유형을 삽입했습니다.

$.ajax({         
data: parameters,         
type: "POST",         
url: ajax_url,
datatype: 'html',         
contentType: "text/html;charset=windows-1252",

간단히 말해서, charset이라는 ASP 파일에서 정의하는 것이 중요합니다. 이상하게도 내 jquery는 windows-1252에서는 작동하지만 ISO-8859-1 charset에서는 작동하지 않습니다.이 경우 jquery ajax 메서드는 예외를 제공합니다.


독일어 특수 문자 (ä, ö, ü)가 포함 된 텍스트 파일을 읽기 위해 많은 제안을 시도했습니다. 결국 :

 $.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);
        }
    });

특수 문자로 읽을 수 있도록했지만 FileName.txt를 UTF-8 형식 으로 명시 적으로 저장 한 후에 만 가능 합니다 . Windows 편집기에서 텍스트 파일을 저장하는 표준 형식은 UTF-8이 아닌 ANSI 이지만 "다른 이름으로 저장"하고 저장 버튼 옆에있는 드롭 박스를 사용하거나 더 나은 편집기를 사용하여 시작하면 변경할 수 있습니다.


모든 것이 UTF-8이어야한다는 데 동의하지 않습니다. ISO 8859에서 완벽하게 작동하도록 만들 수 있습니다. 여기에서 제 답변을 읽어보세요.

stackoverflow의 내 응답


<script type="text/javascript">
  function GetContent(idUser){ 
    $.ajaxSetup({
      url: 'ping.php'
    });

    $.ajax({
      type: "POST",
      url: "blablabla.php",
      dataType: "text",
      data: ({ParamUserID:idUser}),// here we def wich variabe is assiciated
      contentType: "application/x-www-form-urlencoded; charset=iso-8859-1",
      success: function(html) {
        $('#user_specified_content').html(html);
      }
    });     
  }
</script> 

이것은 blabla.php 페이지에서 내 콘텐츠를 가져 오는 스크립트입니다.

성공에 대한 데이터를받을 때 내 억양이 나타나지 않습니다.

.success함수 에서 가져온 데이터에 악센트가있는 데이터를 가져 오기 위해 내 자신이 아주 좋은 작업 솔루션을 찾았습니다.

On my blabla page. I did this to bring a solution to my problem:

I use utf8_encode(place your data here) in my php file. See it in action below:

while( $row = sqlsrv_fetch_array($recordset) )
{                           
    <option value="<?php echo $row["xyz"]; ?>"><?php echo utf8_encode($row["gName"]) . ' | ' . utf8_encode($row["gManagerName"]); ?></option>                           
}

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


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


I came by this question with exactly the same issue as the asker. The answers here are very informing, and I tried out almost every single one of the suggested answers. None of the answers here worked for me though - there might have been a slight difference in my problem. And that seems to be the case for many. I tried so much before ending up with an answer.

So now I'm adding to the already long list of answers, a solution of my own that solved my kind of encoding problem.

I did just two things. In the database connection script I added:

mysql_set_charset('utf8',$connection);

and apart from that:

  • I changed the encoding of all the files to UTF-8

The point is that everything must be of the same encoding. And when creating new php-files, for the scripts it is not enough just to change the encoding in the script - the file itself must be correctly encoded.


Just changed {"type":"GET"} to {"type":"POST"} and worked like a charm with ISO-8859-1


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.


If you are using CodeIgniter you can solve this by adding the following code to your Controller before loading any Views (assuming you have charsetproperly set on your config. If not, just put charset=whateveryouwant.

$this->output->set_header('Content-type: text/html; charset='.$this->config->item('charset'));

The way I did it was to add that line to the constructor of MY_Controller, my superclass for all Controllers, this way I make sure I will have no encoding problems anywhere.

By the way, this doesn't affect JSON returns (which are encoded in UTF-8).


I have tried to read a local json/text file using $.ajax and the encoding didn't work at first.. I got it working by saving the json file as UTF-8 encoding. This can be done simply by windows notepad.. use "save as", and then below the file name you can set the encoding to UTF-8.

good luck!


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

참고URL : https://stackoverflow.com/questions/553463/jquery-ajax-character-encoding

반응형