如何发送原始文本XMLHTTP请求?原始、文本、XMLHTTP

2023-09-10 20:50:10 作者:如此轻信男人

我试图发送一个文本区域字段的文本使用Ajax的PHP文件,文本包含HTML字符的,不应该连接codeD。 使用 FORMDATA 它完美不过它不支持在IE 9和旧版本!我试图通过设置 requestHeader 发送数据为字符串 text / plain的;字符集= UTF-8; 的multipart / form-data的,但它没有工作! 在code我使用的是:

I'm trying to send a textarea field's text to a PHP file using ajax, the text contains HTML characters and should not be encoded. Using FormData it works perfectly however it's not supported in ie 9 and older versions! I tried to send the data as string by setting the requestHeader to text/plain;charset=UTF-8; or multipart/form-data but it didn't work! the code i'm using is:

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?

what's an alternative way to do this in IE 9?

推荐答案

是的,它可以通过修改 headerRequest 数据是这样的:

Yes it can be done by modifying headerRequest and data like this:

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