I'm using jquery get to call an ASP MVC controller. Which returns a partial view. i.e. a bunch of html
In the case of an error I'd like to populate some info for the user but ASP MVC is sending a full page back so I need to grab text out of it.
I've tried:
$('#edit').ajaxError(function (e, xhr, settings, exception) {
var item = xhr.responseText.text();
var response = item.match(/.*<body.*>(.*)<\/body>.*/);
if (!response) {
$(this).html('Error: ' + xhr.status + ' Message:' + xhr.statusText);
}
else {
$(this).html(response);
};
});
But I get Uncaught TypeError: [followed by the contents of xhr.responseText] has no method text
If I call match directly on responseText I get null as a result.
I'm guessing I've got some fundamental misunderstanding going on so if anyone开发者_StackOverflow社区 can help...
You should also modify your regular expression to include newline characters, i.e.
var response = xhr.responseText.match(/.*<body.*>([\s\S]*)<\/body>.*/);
xhr.responseText
is a string (docs), and there is no native method of the String
prototype named text()
. Thus the line below, where you try to call .text()
off the responseText
, causes that error:
var item = xhr.responseText.text();
Since match()
is a method on the String
prototype, you would just call it directly off the responseText
if you're trying to find something therein.
var response = xhr.responseText.match(/.*<body.*>(.*)<\/body>.*/);
Whether it finds anything from there, we'll see ;)
$(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status') ;
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
$('#ttt').html(xhr.responseText.replace(/[\r\n]/g, ' ').match(/<!--t-->([\s\S]*)<!--t1-->/));
}
});
})();
Your regex is going to run into trouble from the newlines in your HTML.
var response = xhr.responseText.replace(/[\r\n]/g, ' ').match(/<body.*>(.*)<\/body>/);
That cleans out the newlines first.
精彩评论