如何用xmlhttp请求发送原始文本

How to send raw text with xmlhttp request?

本文关键字:原始 文本 请求 何用 xmlhttp      更新时间:2023-09-26

我试图使用ajax将textarea字段的文本发送到PHP文件,文本包含HTML字符,不应编码。
使用FormData,它可以完美地工作,但它不支持ie9和更早的版本!我试图通过将requestHeader设置为text/plain;charset=UTF-8;multipart/form-data来发送数据作为string,但它不起作用!我使用的代码是:

var string = '<td clas="tdClass">some text<?php echo $contents; ?></td>';
var data = new FormData();
data.append("data" , string);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);

在ie9中有什么替代方法可以做到这一点?

是的,可以这样修改headerRequestdata:

var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
if(typeof(FormData) == 'undefined'){
    var boundary = '---------------------------' + (new Date).getTime(),//boundary is used to specify the encapsulation boundary of a parameter
        data = "--" + boundary + "'r'n";
        data += 'Content-Disposition: form-data; name="data"'r'n'r'n';//here we specify the name of the parameter name (data) sent to the server which can be retrieved by $_POST['data']
        data += string + "'r'n";
        data += "--" + boundary + "--'r'n";
    xhr.open( 'post', 'writeCode.php', true );
    xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
}else{
    var data = new FormData();
    data.append("data", string);
    xhr.open( 'post', 'writeCode.php', true );
}
xhr.send(data);

如果使用FormData对您来说是正确的,那么在您不能使用它的情况下,实际上您需要做的就是将最后一行替换为:

xhr.send("data="+encodeURIComponent(string));

我认为其他的回答是困惑的,你要求文本"不编码"。表单数据通常被编码为通过HTTP发送,但是当到达服务器时,PHP会对进行解码,完全透明地:您得到的完全是原始文本,无论它可能包含什么特殊字符。(假设您将PHP字符串解释为UTF-8)。

因此,按照您的示例,如果PHP文件包含:
$data = $_POST['data'];

那么PHP $data变量的内容将是字符串'<td clas="tdClass">some text<?php echo $contents; ?></td>'。这与使用FormData方法是一样的。

因为,嗯,它看起来毕竟很简单。这里有一些样品。

只是随机发布文本

// just text
var dest = "http://requestb.in/qwb9y3qw";
var xhr = new XMLHttpRequest();
xhr.open("POST", dest, true);
var myText = "foobar";
xhr.send(myText);

Post一个JSON对象

// post json
var dest = "http://requestb.in/1908jrv1";
var xhr = new XMLHttpRequest();
xhr.open("POST", dest, true);
var myObject = {};
myObject.prop1 = "foo";
myObject.prop2 = "bar";
xhr.send(JSON.stringify(myObject));