【问题标题】:Show the ajax' response in pure text and html format以纯文本和 html 格式显示 ajax 响应
【发布时间】:2019-02-08 14:42:00
【问题描述】:

我想在我的本地电脑上用apache构建一个转发代理,到目前为止我在本地写了一个简单的跨域演示。

这是/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:

/var/www/html/test.html

并以remote 发送(显示在client.html 中),回调到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,我得到如下:

the content on remote webpage<p><b>you are welcome</b></p>

我希望将响应从do.php回调到client.html,以两种格式显示:

  1. 显示为纯文本格式。

    mytext.append(response.responseText);
    

    这是我的尝试,失败了。
    我期望纯文本格式的结果是:

    the content on remote webpage
    you are welcome  
    
  2. 显示为 html 格式。
    我期望的html格式:

我的代码格式:

the content on remote webpage<p><b>you are welcome</b></p>

对于这两种情况,我如何修复我的代码mytext.append(response);,也许在这里?

【问题讨论】:

  • 我不知道你的问题到底是什么。
  • 你不习惯蹩脚的英语。
  • 所以你只想要没有 HTML 标记的文本?
  • “你不习惯破英语” 我在这个网站上已经 10 年了,我对破英语没有任何问题。我只是不知道你的问题到底是什么。

标签: javascript jquery ajax string text


【解决方案1】:
  1. 获取html格式,你的代码就OK了,
  2. 如果你想获得纯文本格式,请使用 jQuery(...).text() 函数从响应中删除 html 标签。

    ...
    mytext = document.getElementById("remote");
    mytext.append($(response).text());
    ...
    

看看:How to strip HTML tags with jQuery?

【讨论】:

  • 正确的代码显示结果为the content on remote webpage&lt;p&gt;&lt;b&gt;you are welcome&lt;/b&gt;&lt;/p&gt;,而不是html格式。
  • DOM 的 append() 是什么?
【解决方案2】:

基于 jquery 的 append 方法解决了这两个问题,而不是我的 privious 代码中的 javascript 的 append 方法。

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 js

mytext = document.getElementById("remote");
mytext.append(response);

以上两行的输出结果如下。

content on remote webpage<p><b>you are welcome</b></p>

【讨论】:

    猜你喜欢
    • 2022-08-05
    • 2019-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多