3

我正在尝试textarea使用 ajax 将字段的文本发送到 PHP 文件,该文本包含 HTML 字符并且不应该被编码。
使用FormData它可以完美运行,但 ie 9 和更早的版本不支持它!我试图string通过设置requestHeaderto text/plain;charset=UTF-8;or来发送数据,multipart/form-data但它没有用!我正在使用的代码是:

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

在 IE 9 中执行此操作的另一种方法是什么?

4

3 回答 3

3

如果 usingFormData适合您,那么在您无法使用它的情况下,实际上您需要做的就是将最后一行替换为:

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方法相同。

于 2016-08-23T19:22:52.820 回答
2

是的,它可以通过修改来完成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);
于 2013-04-06T10:22:04.303 回答
0

因为,好吧,它毕竟看起来很简单。这是更多示例。

随便发个文字

// just text
var dest = "http://requestb.in/qwb9y3qw";

var xhr = new XMLHttpRequest();
xhr.open("POST", dest, true);

var myText = "foobar";
xhr.send(myText);

发布 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));

于 2014-09-28T21:10:06.190 回答