.replace不在xmlhttp.responseText-Javascript上工作

.replace不在xmlhttp.responseText-Javascript上工作,javascript,ajax,Javascript,Ajax,我有: if(xmlhttp.readyState==4&&xmlhttp.status==200) { cu=$(“#box1”).val(); cur=xmlhttp.responseText; cur=cur.replace(cu,“”+cur+”); $(“.box2”).html(cur); } 我试过了,但替换却没有发生 当我将cur更改为只有一个普通文本值(cur='my name is….';)时,它工作正常 我已尝试将替换行更改为:cur=cur.replace(cu,'fo

我有:

if(xmlhttp.readyState==4&&xmlhttp.status==200)
{
cu=$(“#box1”).val();
cur=xmlhttp.responseText;
cur=cur.replace(cu,“”+cur+”);
$(“.box2”).html(cur);
}
我试过了,但替换却没有发生

当我将
cur
更改为只有一个普通文本值(
cur='my name is….';
)时,它工作正常

我已尝试将替换行更改为:
cur=cur.replace(cu,'foundit')-还是没什么

这与AJAX请求发生的位置在同一个函数中


有什么想法吗?

听起来
cu
在字符串
cur
中根本找不到。将其更改为您知道的字符串文字,以确保您实际替换了某些内容。

Javascript是异步的。您是否确认正在执行“如果”语句?第一次测试时,这些条件很有可能不满足

第一个测试:
添加警报('x')在该“if”语句中

第二个测试:延迟“如果”语句

 if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {

    cu=$("#box1").val();
    cur=xmlhttp.responseText;

    cur=cur.replace(cu,'<strong>'+cur+'</strong>');  

     $(".box2").html(cur);

 }
setTimeout('fncCallBack()',5000);
函数fncCallBack(){
if(xmlhttp.readyState==4&&xmlhttp.status==200)
{
cu=$(“#box1”).val();
cur=xmlhttp.responseText;
cur=cur.replace(cu,“”+cur+”);
$(“.box2”).html(当前的_响应);
}
}

如果您修复了一个可能是复制粘贴错误的问题,那么您的代码可以正常工作。您正在设置
.html(当前\u响应)
,但从未定义
当前\u响应

但我怀疑它是否能按你希望的方式工作。如果
$(“#box1”).val()
world
,而
xmlhttp.responseText
hello world hello world
,则结果将只替换world的第一个实例,并将替换为整个响应字符串,因此您将得到:

setTimeout('fncCallBack()', 5000);

function fncCallBack() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {

    cu=$("#box1").val();
    cur=xmlhttp.responseText;

    cur=cur.replace(cu,'<strong>'+cur+'</strong>');  

     $(".box2").html(current_response);

 }
}
hellohello world hello worldhello world
这就是你想要的吗?如果只替换匹配字符串的第一个实例是可以的,那么您可能需要:

hello <strong>hello world hello world</strong> hello world
cur=cur.replace(cu,$&);
编辑:但要替换匹配字符串的每个实例,需要使用正则表达式:

cur = cur.replace(cu, "<strong>$&</strong>");
cu=$(“#box1”).val();
var re=new RegExp(cu.replace(/[\[\]\\.*+?^${}()\/\\;]/g,“\\$&”),“g”);
cur=xmlhttp.responseText;
cur=cur.replace(关于“$”和“”);
$(“.box2”).html(cur);

工作演示:

您在responseText中是否有值,它是否为空。。尝试警报responseText以检查..?它不是空的,因为我在另一个div中显示该值,它会显示..我也尝试了。还是没什么。我知道问题在于cur是xmlhttp.responseText,因为当我将cur更改为普通字符串(cur='hello there';)时,它可以正常工作。由于某些原因,它无法替换xmlhttp.responseText中的内容,因为我更改了行:$(“.box2”).html(当前的_响应);美元(“.box2”).html(cur);whicl将在div box2中显示最终字符(带替换字符的字符串)。确实如此。所以不是if语句尝试了延迟,还是没有。我忘记了setTimeout调用的()。更新了。啊,你刚才指出了问题中的一个编辑错误,对不起,我会纠正的。它应该是.html(cur)。基本上,我想替换cu中的任何字符,也就是cur中的字符。我需要替换cu中的每个字符,而不仅仅是第一个。@Nav-要替换每个匹配的字符,必须使用正则表达式。看我的答案的编辑。啊,这就成功了。还有一件事:你知道在responceText(cur)中转义一些html内容的方法吗?因为我在那里有一些div标记(cur=responceText=actual value),我不希望替换生效。这可能吗?@Nav-我以前至少回答过两次这个问题。见和。
cu = $("#box1").val();
var re = new RegExp(cu.replace(/[\[\]\\.*+?^${}()\/|]/g, "\\$&"), "g");
cur = xmlhttp.responseText;
cur = cur.replace(re, '<strong>$&</strong>');
$(".box2").html(cur);