[英]How can I use an if statement in a $.jQuery ajax post's success:?
我有一個Web應用程序和一個服務器端應用程序,當服務器端應用程序成功保存Web應用程序的POST時,它會以“已保存”響應,否則會返回“錯誤”,我該如何創建IF
語句來檢查響應?
function send(family){
$.ajax({
type: 'POST',
url: 'http://sistema.agrosys.com.br/webpro/webadm/wcgarvore',
data: family,
success: function(data, textStatus ){
console.log('DONE: Request has been successfully sent');
if(data === 'error'){ //how can I do it
alert("ERR:\n\ncouldn't save");
}
},
error: function(xhr, textStatus, errorThrown){
alert('Envio Falhou\n\nERR: '+errorThrown);
}
});
}
試試這個並修剪返回字符串if($.trim(data) === 'error')
。 這可能是空白問題。 您可以確定是否在控制台中簽到並查看返回了什么。 整理收益,然后比較。
如果服務器以正確的錯誤消息響應,那么它將在成功處理程序中收到。
因此,成功處理程序將以對象或字符串的形式接收數據。
現在,在這種情況下,您期望它是字符串“錯誤”並且不檢查對象,它可能是data.status或data.textstatus。
因此,在if條件之前添加console.log(data)並檢查。
console.log(data);
if(data.status == 'error'){}
如果數據在對象檢查中,請檢查相應條件。
考慮以下示例(已通過PHP 5.5.9和Firefox 39測試)。
ajaxtest.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function() {
$('#sendAjax').click(function () {
send($('input[name="param"]').val());
});
});
function send(test_data){
$.ajax({
type: 'POST',
url: 'ajaxtest.php',
data: { msg: test_data },
success: function(data, textStatus ){
console.log('DONE: Request has been successfully sent');
console.log(data);
if(data === 'error'){
$('#response').text('error');
$('input[name="param"]').val('get_success');
} else {
$('#response').text('success');
$('input[name="param"]').val('get_error');
}
},
error: function(xhr, textStatus, errorThrown){
alert('Envio Falhou\n\nERR: '+errorThrown);
}
});
}
</script>
</head>
<body>
<button id="sendAjax">Send Ajax</button>
<div id="response"></div>
<input type="hidden" name="param" value="get_success" />
</body>
</html>
ajaxtest.php
<?php
if ($_REQUEST['msg'] == 'get_error') {
echo "error";
} else {
echo "success";
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.