我使用jquery和ajax提交表单而不重新加载页面,然后根据结果(无论是成功还是错误)我在两个不同的div中打印消息.由于ajax中的成功和错误只检查客户端/服务器连接,因此当查询成功时我会回复PHP中的一些内容,并根据我的条件决定如何处理消息.Jquery/ajax部分看起来像那样(通常我使用两个不同的div,但为了简化示例,我将使用警报):
success: function (result) {
if (result == 'success') {
alert("Success!");
} else {
alert("There was an error.");
}
},
Run Code Online (Sandbox Code Playgroud)
这很好用,但我想提高它的可用性.
现在的问题是:我可以使用if (result ==
像str.match这样的部分内容吗?例如,如果运行查询时遇到一些问题,我会在php中回显我可以在echo "Error: >error description here<";
某种程度上使用str.match(/^Error/)
我的if条件并回显整个消息吗?
Tom*_*ech 18
不要将字符串匹配用于此任务.使用HTTP响应代码 - 这就是他们的目的!http_response_code
PHP中的函数是为此目的而设计的:
<?php
if ( /* error condition */ ) {
http_response_code(400); // "Bad request" response code
echo 'Invalid parameters';
}
else {
echo 'Success'; // response code is 200 (OK) by default
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用jQuery done
和fail
回调来分别处理这两种情况:
$.ajax(url, params)
.done(function(response) { alert('all good: ' + response); })
.fail(function(response) { alert('error: ' + response); })
Run Code Online (Sandbox Code Playgroud)
要检查message
启动Error:
是否可以使用indexOf
:
if (result.indexOf('Error:') === 0) {
// Starts with `Error:`
}
Run Code Online (Sandbox Code Playgroud)
indexOf
将返回字符串中找到的index
起始0
位置.Error:
result
参考:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
该
indexOf()
方法返回第一次出现的指定值的调用String对象中的索引,从fromIndex开始搜索.如果未找到该值,则返回-1.
归档时间: |
|
查看次数: |
1207 次 |
最近记录: |