AJAX: post method with UTF-8

后端 未结 1 2001
感动是毒
感动是毒 2021-01-25 23:53

I\'m trying to send data as UTF-8 over Ajax, but it\'s changing some data in unicode. I\'ll explain it with two short examples:

A simple POST (

相关标签:
1条回答
  • 2021-01-26 00:17

    i use alot ajax and always use only utf8 and never had a problem , i'm mostly on chrome and safari ios

    maybe try changing ur ajax script by removing all the headers.and using the new FormData (should work on most modern browsers) ... sure not on all.

    document.forms[0] means it takes all the fields from first form in your page. else give it an id and call document.getElementById('myform') i also don't use anymore readyState... onload

    to return the response in postresponsefunction u write this.response

    var fd=new FormData(document.forms[0]),
    c=new XMLHttpRequest();
    c.open('POST',strURL);
    c.onload=postresponsefunction;
    c.send(fd);
    

    here is a complet working php script with post & ajax file is named 'test.php'

    <?php
    if($_REQUEST){
    print_r($_REQUEST);
    }else{
    ?>
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>postajax</title>
    <script>
    var 
    rf=function(){
     document.getElementsByTagName('div')[0].innerText=this.response;
    },
    sf=function(e){
     e.preventDefault();e.stopPropagation();
     var fd=new FormData(document.getElementsByTagName('form')[0]),
     c=new XMLHttpRequest();
     c.open('POST','test.php');
     c.onload=rf;
     c.send(fd);
    };
    window.onload=function(){
     document.getElementsByTagName('form')[0].onsubmit=sf;
    }
    </script>
    </head>
    <body>
    <form>
    <input type="text" name="mytext"><input type="submit" value="submit">
    </form><div></div>
    </body>
    </html>
    <?php
    }
    ?>
    

    ie

    if (!window.XMLHttpRequest) {
      window.XMLHttpRequest = function() {
        return new ActiveXObject(”Microsoft.XMLHTTP”);
      };
    }
    
    0 讨论(0)
提交回复
热议问题