[英]How to send raw text with xmlhttp request?
我正在尝试使用 ajax 将textarea
字段的文本发送到 PHP 文件,该文本包含 HTML 字符,不应进行编码。
使用FormData
它可以完美运行,但是它在 ie 9 及更旧版本中不受支持! 我试图通过将requestHeader
设置为text/plain;charset=UTF-8;
来将数据作为string
发送text/plain;charset=UTF-8;
或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 中执行此操作的另一种方法是什么?
如果使用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>'
'<td clas="tdClass">some text<?php echo $contents; ?></td>'
. 这与您使用FormData
方法的情况相同。
是的,它可以通过像这样修改headerRequest
和data
来完成:
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);
因为,好吧,毕竟它看起来很简单。 这里还有一些示例。
只需发布随机文本
// 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.