Ajax或JavaScript:根据服务器响应更改样式

时间:2010-08-09 19:12:51

标签: javascript ajax coding-style responsetext

嘿,我想根据结果更改字体颜色或responseText。例如,如果responseText未找到,我想将字体颜色设置为红色。否则,它将是黑色的。它当前正在显示正确的responseText;我只是想在必要时改变颜色。这是我目前的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中的表格中:

                    <tr>
                        <td class="ajax_msg">
                            <div id="location_div"></div>                           
                        </td>
                        <td>&nbsp;</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> 

欢迎任何建议。提前谢谢!

1 个答案:

答案 0 :(得分:0)

像这样修改你的代码:

  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;
  }

您基本上检查条件中的响应文本:

if (getLocation.responseText === 'NOT FOUND'){

使用style更改颜色,如下所示:

dv.style.color = "red";

请注意,dv变量表示您将显示之前使用此行设置的响应文本的div:

var dv = document.getElementById("location_div");

<强>更新

尝试使用else条件,因为默认情况下你可能有红色:

 if (getLocation.responseText === 'NOT FOUND'){
   dv.style.color = "red";
 }
 else {
  dv.style.color = "black";
 }