The code below always returns $('.ErrorMessage', result).length
as 0. I don't understand why though. Ideas?
AJAX Request
$.ajax({
type: "POST",
url: action,
dataType: "html",
data: serializedForm,
success: function (result) {
开发者_开发百科if ($('.ErrorMessage', result).length > 0) {
$('#editSurveyModal').append(result);
}
else {
alert('fail');
}
},
error: function (request, status, error) {
alert('save fail');
}
});
'result' Returns.. (verified with an alert)
<div id="ErrorMessage" class="ErrorMessage">
<div>
Please correct the following errors before saving.
</div>
<div style="text-align: left">
<ul>
<li>Test</li>
</ul>
</div>
</div>
What Im Trying to Do
I'm trying to see if the result is the above error partial view by checking for the ErrorMessage class somewhere in the result.
I dealt with this exact same problem myself once.
You can't .find()
it, because the element you're trying to find is at the root level of the collection.
(Note that $(selector, result);
is a shorthand syntax for $(result).find(selector);
)
However, .filter('.ErrorMessage')
will match it, just fine.
(Incidentally, you'll run into the same problem when you pass a whole HTML document into the jQuery() function - then the <html>
, <head>
and <body>
elements get stripped away.)
What you should do (to catch most/all edge-cases) is the following:
if ( $( '.ErrorMessage', $('<div/>').html( result ) ).length > 0 )
...
...and Bob's your uncle. :-)
You can use jQuery to instantiate DOM elements from result first (adding them to a container), and then check:
$('.ErrorMessage', $("<div/>").html(result)).length
You could deal with the result variable directly (as a string), and just use a regular expression to find the string "ErrorMessage" within it:
result.match('/ErrorMessage/')
Your return is valid xml, so you can use 'xml' as dataType and get a document(instead of a string if you use 'html')
精彩评论