jQueryAJAX-基于PHP页面数据的有条件成功结果
jQuery AJAX - conditional success result based on data from PHP page
我用jQuery设置了第一个AJAX调用,并且运行良好。我需要做的最后一个更改是检查被调用的PHP页面的结果是否有任何数据库错误,并在需要时显示错误。
以下是我当前的Javascript,其中有一些注释,我想根据结果进行分支:
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){
var storeManager = $("#storeManager").val();
$.post('editProject.php', { type: 'storeManager', storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
// if there was a database error from the editProject.php page it will be returned in this format:
// Error: Database Error 456
// If there is an "Error: " string in the result I would like to do the following
$("#ajaxAlert").addClass("alert alert-danger");
$("#ajaxAlert").html(data);
// If there is no "Error: " string in the result I would like to do the following
$("#storeManagerRow").addClass("success");
$("#storeManagerRow").removeClass("danger");
$("#ajaxAlert").hide();
}).fail(function () {
// no data available in this context
$("#storeManagerRow").addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
//append error to the div using its ID
$("#ajaxAlert").html(data);
});
});
});
</script>
我是jQuery和AJAX的新手,边做边学——只是不知道如何根据PHP页面的结果(数据)进行分支。
不从PHP脚本返回html,而是返回一个JSON对象。
为了获得成功,您可以返回一个data
对象,如下所示:
{
html: '<p>lorem ipsum</p>'
}
对于应用程序错误的结果,您可能会有一个data
对象,如下所示:
{
error: true,
html: '<p>Error: Database Error 456</p>'
}
在回调中,只需检查error
属性的存在:
if (data.error) {
$("#ajaxAlert").addClass("alert alert-danger").html(data.html);
// ...
return; // stop the execution of this function right here
}
相关文章:
- 通过js在新选项卡中有条件地打开url
- jQuery-有条件地附加HTML
- 有条件更新d3.js力图中节点的最佳方法
- Woocommerce产品选项有条件
- 有条件地在选项标记中应用布尔属性
- ADF:有条件地加载javascript资源
- 如何有条件地更改角度中的orderBy参数
- 无法在有条件呈现的富:面板上提交h:form
- 有条件地与react路由器链接
- 有条件地运行javascript函数-Razor,HTML
- 如何使用图表包装函数有条件地格式化谷歌可视化表单元格
- CSS根据属性的可用性有条件地应用样式
- 将字段设置为有条件地使用所需的字段验证器
- 将https替换为有条件的锚标记Javascript
- JavaScript while循环没有'不能在有条件的情况下工作
- 如何用d3有条件地移除元素
- 有条件刷新页面-如何设置引用人
- 有条件地创建ajax url参数以与jQuery Validate一起使用
- jQueryAJAX-基于PHP页面数据的有条件成功结果
- 如果登录成功,则有条件地关闭引导模式面板