我得到的输出是这个html:
<form action="?next=/pm/write/" method="post">
<label>Recipient:</label>
<ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="recipients" id="id_recipients" />
<br />
<label>Subject:</label>
<ul class="errorlist"><li>This field is required.</li></ul>
<input id="id_subject" type="text" name="subject" maxlength="120" />
<br />
<label>Body:</label>
<textarea id="id_body" rows="12" cols="55" name="body"></textarea>
<input type="submit" value="Send" class="yes" />
<input type="reset" value="Clear" class="no" />
</form>
Javascript:
$('#ajaxForm input[type="submit"]').live('click', function(e) {
$.ajax({
url: '/pm/write/',
type: 'post',
data: $('#ajaxForm form').serialize(),
success: function(output) {
if (output.search('errorlist') != -1) {
alert('error found');
}
else {
alert('all good');
}
}
});
e.preventDefault();
});
正如你所看到的输出确实包含字符串"errorlist",我得到的错误是"error found"。这很好,但问题是,我总是得到这个警报,即使输出不包含"errorlist"字符串,如何解决这个问题?
更新下面是没有错误时的输出:
<form action="" method="post">
<label>Recipient:</label>
<input type="text" name="recipients" id="id_recipients" />
<br />
<label>Subject:</label>
<input id="id_subject" type="text" name="subject" maxlength="120" />
<br />
<label>Body:</label>
<textarea id="id_body" rows="12" cols="55" name="body"></textarea>
<input type="submit" value="Send" class="yes" />
<input type="reset" value="Clear" class="no" />
</form>
返回更结构化的数据要比返回一大块HTML要好得多。考虑返回如下JSON结构:
{
error: false,
errormsg: 'blah blah blah',
html: '<html>.....</html>'
}
。那就只需要一个简单的
if (output.error) {
alert(errormsg);
} else {
...
}
好的,如果更改服务器端不是一个选项,试试这个:
if (output.search(/errorlist/) == -1) {
alert ("error found");
} else {
alert ("all good");
}
搜索调用需要一个正则表达式,而不仅仅是一个普通的字符串。
尝试更改datattype -parameter(或添加,如果你不使用jQuery.ajaxSetup())
$.ajax({
url: '/pm/write/',
type: 'post',
data: $('#ajaxForm form').serialize(),
dataType: 'html', //or dataType: 'text'
success: function(output) {
if (output.search('errorlist') != -1) {
alert('error found');
}
else {
alert('all good');
}
}
});