使jQuery.ajax()HTTP请求的行为类似于普通的HTML

时间:2017-11-23 11:10:03

标签: javascript jquery html ajax

所以,我正在使用jQuery.ajax()来发出HTTP请求,并在我的页面上显示一个显示为纯文本的XML提要。

在此之前,我提示用户键入要在该特定Feed中搜索的单词。

问题在于,如果找到该单词,则在用户窗口上显示为文本时突出显示该单词,例如说背景颜色为红色。我已经尝试了所有的东西,但我似乎无法使它工作,我怀疑因为我需要先以某种方式解析它。

以下是代码:

function search(ans) {
var url = "SOME_XML_FEED"
$.ajax({
    url: url,
    dataType: "html",
    crossDomain: "true",
    success: function (response) {
        var n = response.search(ans); //Where the word is found.
        var ansReplacement = '<p style="color: #ffffff; background-color: #ff0000">' + ans + '</p>';
        ans = response.replace(ans, ansReplacement);
        if (ans === response) {
            alert("The string was not found in a text with " + response.length + " letters.");
        } else {
            alert("The string was found at position: " + n + " in a text with " + response.length + " letters.");
        }
        $('#demo').text(ans);
    }

提前致谢。

2 个答案:

答案 0 :(得分:1)

使用全局正则表达式查找字符串的所有匹配项,然后使用jQuery的.html()方法分配修改后的HTML,而不是.text()

let toHighlight="in",
	$sampleText = $("#sampleText"),
	originalText = $sampleText.text(),
	highlightedText = originalText.replace(new RegExp(toHighlight, "gi"), `<span class="highlight">${toHighlight}</span>`)

$sampleText.html(highlightedText)
.highlight {
  color: #ffffff;
  background-color: #ff0000
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sampleText">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras tempus, sem at vehicula bibendum, magna arcu accumsan massa, eget porta velit odio ac lectus. Nullam erat sapien, consectetur in tortor eget, rhoncus commodo neque. Maecenas accumsan molestie arcu ac scelerisque. Etiam molestie velit in dolor rutrum, at vehicula mauris volutpat. Ut lobortis dui in maximus elementum. Maecenas quis orci non ligula lobortis aliquam.</div>

答案 1 :(得分:0)

您正在使用“文本”功能将HTML粘贴到“#demo”div中。这剥离了html。请尝试使用“html”功能:

public class CallingClass{
    CallingClass(){
        ClassTwo thread = new ClassTwo();
        thread.start();
    }

    public void someMethod(){}

}

public class ThreadClass extends Thread{
    public void run(){
        //Some thread logic
        CallingClass.someMethod();
    }
}