jQuery AJAX添加'%20'作为空格,普通的javascript xmlhttp请求没有

时间:2013-08-22 13:24:01

标签: jquery ajax encodeuricomponent

我有jQuery AJAX这个功能可以从CKEDITOR text_area中检索数据并通过AJAX将其发送到.php文件:

function saveEmailData(){
    var text_body = encodeURIComponent(CKEDITOR.instances.text_body.getData());

    $.ajax({
        url: 'al_ajax.php',
        cache: false,
        data: {area: text_body, use: 'savemaildata'},
        type: 'POST',
        success: function(result){
                    alert(result);
                 },
        error: function(result){
                    alert('Error');
                },
    });
}

PHP:

$area = $link->real_escape_string($_POST['area']);

$insert_query = $link->query("INSERT INTO ALLARME_EMAIL_TEXT (area)
                                VALUES ('$area')
                              ON DUPLICATE KEY UPDATE
                                area = '$area'
                              ")
                              or die('Error.');

if($insert_query){          
    echo 'OK!';
}

问题是使用jQuery AJAX,我会在数据库%20上使用正常的javascript function,这不会发生:我总是使用。为什么呢?

function saveEmailData(){
    var text_body = encodeURIComponent(CKEDITOR.instances.text_body.getData());

    if(window.XMLHttpRequest) {
      xmlhttp=new XMLHttpRequest();     
    } else {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        alert(xmlhttp.responseText);
      }
    }

xmlhttp.open("POST","al_ajax.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("area="+text_body);
}

1 个答案:

答案 0 :(得分:2)

这不是jQuery的错。你两次逃过文本正文:

var text_body = encodeURIComponent(CKEDITOR.instances.text_body.getData());

注意jQuery已经encodeURIComponent传递给data传入的任何内容。解决方案就是摆脱它。

function saveEmailData(){
    var text_body = CKEDITOR.instances.text_body.getData();

    $.ajax({
        url: 'al_ajax.php',
        cache: false,
        data: {area: text_body, use: 'savemaildata'},
        type: 'POST',
        success: function(result){
                    alert(result);
                },
        error: function(result){
                    alert('Error');
                },
    });
}