开发者

Ajax: Change responseText font color based on result

Programmers here have been extremely helpful in resolving issues for me in the past, so I thought I'd ask an Ajax question. It's probably a simple fix, but I'm new to Ajax.

What I'd like to do is change the style of the respo开发者_运维百科nseText to red if the result is the pharase, "NOT FOUND". Otherwise the text will be black. Here is the script I'm using:

 <script type="text/javascript">
  <!-- 
  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;
  }
  //-->
 </script>

Here is the HTML:

...
<table>
    <tr>
        <td class="ajax_msg">
         <div id="location_div"><div>       
        </td>
    </tr>
</table>
...


You should use css for those styles:

JS:

if (reponseText == "NOT_FOUND") 
   document.getElementById("location_div").className = "error";
else
   document.getElementById("location_div").className = "success";

CSS:

.error
{
  color: red;
}
.success
{
  color: black;
}

Edit: Corrected .class to .className (this would be easier with jquery)


In my honest opinion, jQuery is the best way to go with AJAX calls. It would also shorten your code by a lot!

Head Section

...
<script type="text/javascript" src="js/jquery.1.4.2.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
      $.get('/PP', { PAGE: 'GETLOCATIONNAME', ROUTINGNUM: location }, function(data) {
          if(data == "NOT_FOUND") {
              $('#location_div').addClass('error');
          } else {
              $('#location_div').addClass('success');
          }
      });
  });
</script>

Then you could use the same CSS as gustavogb.
Now, this may be a bit different from what you want it to do exactly, but as you can see, jQuery has significantly shortened the amount of code for an AJAX call. Also, I'm unsure of where the variable 'location' comes from, but I included in the call.

Good luck and if you need more help, you can read more at jQuery.com.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜