views:

673

answers:

1

After a post with "$.ajax()", I sometimes receive an exception from the server. You can see a part of the returned HTML below:

<html>
<head>
  <title>MyMessage</title>
  <style>
    /* ... */
  </style>
</head>

<body bgcolor="white">  
  <span>
    <H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
    <h2> <i>MyMessage</i> </h2>
  </span>
  <b> Exception Details: </b>System.Exception: MyMessage<br><br>
  <!-- ... -->

  [Exception: MyMessage]
    lambda_method(ExecutionScope , ControllerBase , Object[] ) +159
    ...
 </body>
 </html>

I'd like to get the value of the title tag ("MyMessage") How can I do this with jQuery?

+4  A: 

In short, I don't think you can. jQuery only allows you to select tags that can be placed within a div tag. Your title tag doesn't qualify.

See this answer for more information.

Other options...

Partial HTML:
There are other options. You could return partial HTML whenever you experience an error. Instead of <html><body><p>Error</p></body></html> you return <p>Error</p>.

JSON:
You could also go with something a bit cleaner, like JSON. Since you're working with ajax anything, you could send back the following string:

{'status':'failed','message':'Something bad happened'}

And then access the 'message' value within your client-side script.

Proxy Script:
By using a proxy script written in either C# or PHP you can get access to the value of a title field, and return that to your jQuery ajax process.

IFrame Method:
Load the results up in an iframe, and then get the value through iframe.document.title. You can make your iframe 1x1, so it's not visible.

Jonathan Sampson
Other client side solution maybe ?
Kris-I
Go with a different type of data. Send JSON back instead.
Jonathan Sampson
Jonathan Sampson that's will work with this sent code (in the answer) ? http://stackoverflow.com/questions/1170230/asp-net-mvc-with-jquery-catch-exception-display-error-message
Kris-I
@Jonathan Sampson : I don't decide what I return. In the ASP.NET MVC I throw an exception like this : throw new Exception("MyMesssage"); the only think I want it's the this message only to display
Kris-I
Look at my last suggestion, concerning the iframe.
Jonathan Sampson
@Jonathan Sampson : not visible (1x1) and tried (display:none) but in both cases, the page behavior change :(
Kris-I
@Jonathan Sampson and the others :http://stackoverflow.com/questions/1034881/what-is-the-best-practice-for-parsing-remote-content-with-jquery/1049430#1049430This solution works fine. It's not very "clean" but workThanks for your time
Kris-I
Well doesn't work with IE :(
Kris-I