Ajax或JavaScript:根据服务器响应更改样式 [英] Ajax or JavaScript: Changing Style According to Server Response
问题描述
嘿,我想根据结果更改字体颜色或responseText。例如,如果responseText为NOT FOUND,我想将字体颜色设置为红色。否则,它将是黑色的。它当前显示正确的responseText;我只是想在需要时改变颜色。这是我当前的Ajax:
Hey, I'd like to change the font color or the responseText based on the result. For example, if the responseText is NOT FOUND, I'd like to font color to be red. Otherwise, it will be black. It's currently displaying the correct responseText; I just want to change the color when necessary. Here is my current Ajax:
function newXMLHttpRequest()
{
var xmlreq = false;
if (window.XMLHttpRequest)
{
xmlreq = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try
{
xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e2)
{
alert("Error: Unable to create an XMLHttpRequest.");
}
}
return xmlreq;
}
function getLocation(location)
{
var getLocation= newXMLHttpRequest(); // sending request
getLocation.open("GET", "/PP?PAGE=GETLOCATIONNAME&ROUTINGNUM=" + location, false);
getLocation.send(null); // getting location
document.getElementById("location_div").innerHTML = getLocation.responseText;
}
responseText将在HTML中的一个表中:
The responseText will be within a table in the HTML:
<tr>
<td class="ajax_msg">
<div id="location_div"></div>
</td>
<td> </td>
</tr>
<tr>
<td>
<div class="column1">
<p class="label_top">
*Routing Number</p>
<p class="field_top"><input type="text" id="location" name="location" size="28" maxlength="9" onblur="getLocation(this.value);" /></p>
欢迎任何建议。提前感谢!
Any suggestions are welcome. Thanks in advance!
推荐答案
修改代码如下:
function getLocation(location)
{
var getLocation= newXMLHttpRequest(); // sending request
getLocation.open("GET", "/PP?PAGE=GETLOCATIONNAME&ROUTINGNUM=" + location, false);
getLocation.send(null); // getting location
var dv = document.getElementById("location_div");
if (getLocation.responseText === 'NOT FOUND'){
dv.style.color = "red";
}
dv.innerHTML = getLocation.responseText;
}
您基本上在条件中检查响应文本:
You basically check the response text in condition with:
if (getLocation.responseText === 'NOT FOUND'){
并使用 style
更改其颜色,如下所示:
And change its color using style
like this:
dv.style.color = "red";
请注意, dv
你将显示用此行设置的respones文本:
Note that dv
variable represents the div where you will be showing the respones text which was set earlier with this line:
var dv = document.getElementById("location_div");
更新:
尝试使用else条件,因为默认情况下可能是红色:
Try with else condition because possibly you have red color by default:
if (getLocation.responseText === 'NOT FOUND'){
dv.style.color = "red";
}
else {
dv.style.color = "black";
}
这篇关于Ajax或JavaScript:根据服务器响应更改样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!