以纯文本和html格式显示ajax的响应 [英] Show the ajax' response in pure text and html format
问题描述
我想使用apache在本地PC上构建转发代理,到目前为止,我在本地编写了一个简单的跨域演示.
I would like to build a forward proxy on my local pc with apache, So far I wrote a simple cross-domain demo with proxy locally.
这是/var/www/html/client.html
文件:
<script src="http://127.0.0.1/jquery-3.3.1.js"></script>
<script>
function Ajax( ) {
var url = 'http://127.0.0.1/do.php?url=http://127.0.0.1/test.html';
$.ajax(url, {
type:"GET",
dataType: 'html',
crossDomain: true,
success:function(response){
mytext = document.getElementById("remote");
mytext.append(response);
},
error: function (e) {
alert("error");
}
});
};
</script>
<input type="button" value="show content" onclick="Ajax();">
<p id="remote">the content on remote webpage</p>
这是/var/www/html/do.phpdo.php
文件,它用作代理,获取目标URL:
Here is the /var/www/html/do.phpdo.php
file, it function as a proxy, get target url:
/var/www/html/test.html
并以remote
发送(显示在client.html中),回调到client.html
.
and send as remote
(showed in client.html), callback into client.html
.
<?php
header('Access-Control-Allow-Origin: *');
echo file_get_contents($_GET['url']);
?>
/var/www/html/test.html
文件:
<p><b>you are welcome</b></p>
要在浏览器中输入127.0.0.1/client.html
并单击按钮show content
,我将得到以下信息:
To input 127.0.0.1/client.html
in browser and click button show content
, what I get is the following:
the content on remote webpage<p><b>you are welcome</b></p>
我希望响应从do.php
回调到client.html
,以两种格式显示:
I want the response callbacked into client.html
from do.php
, showed in two kinds of format:
-
以纯文本格式显示.
mytext.append(response.responseText);
这是我的尝试,失败.
我以纯文本格式期望的结果是:
It is my try, failure.
The result what i expect in pure text format is:
the content on remote webpage
you are welcome
显示为html格式.
我期望的html格式:
showed as html format.
What I expect html format:
我用我的代码得到的格式:
What I get format with my code:
the content on remote webpage<p><b>you are welcome</b></p>
在两种情况下,如何在这里修复代码mytext.append(response);
?
How do I fix my code mytext.append(response);
, maybe here, for the two cases?
推荐答案
解决了基于jquery的append方法(而不是我的私有代码中javascript的append方法)的两个问题.
Solved the two issue based on jquery's append method ,instead of javascript's append method in my privious code.
1.纯文本格式
mytext = $("#remote");
mytext.append("<br/>");
mytext.append($(response).text());
2.html格式
mytext = $("#remote");
mytext.append("<br/>");
mytext.append(response);
在javascript中,ParentNode.append()允许附加DOMString对象.
ParentNode.append()
In javascript, ParentNode.append() allows to append DOMString object.
ParentNode.append() in js
mytext = document.getElementById("remote");
mytext.append(response);
上面的两行将以下内容作为输出.
The two lines above result in the following as output.
content on remote webpage<p><b>you are welcome</b></p>
这篇关于以纯文本和html格式显示ajax的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!