以下是我的AJAX功能代码:
$('#request_form').submit(function(e) {
var form = $(this);
var formdata = false;
if (window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url : 'xyz.php',
type : 'POST',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
success: function(response) {
//Here I'm facing issue in checking whether the $response[error_message] is empty or not
if (!response.error_message)
alert(response.error_message);
}
});
e.preventDefault();
});
以下是来自PHP的内容。此内容已使用方法json_encode()
{
"error_message": "Id can't be blank<br>Please select Date<br>Image can't be blank<br>"
}
我想检查数组响应[error_message]是否为空,然后我想在警告框中显示内容,否则什么都不做。
请帮助我。
提前感谢。
答案 0 :(得分:1)
试试这个:
<script>
$('#request_form').submit(function(e) {
//This should be the first line
e.preventDefault();
var form = $(this);
var formdata = false;
if (window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url : 'xyz.php',
type : 'POST',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
success: function(response) {
var responseObject = $.parseJSON(response);
//Here I'm facing issue in checking whether the $response[error_message] is empty or not
if (responseObject.length != undefined && responseObject.length > 0)
alert(responseObject.error_message);
}
});
});
</script>
答案 1 :(得分:0)
使用:
if ( response.hasOwnProperty('error_message') && '' != response.error_message ){
alert(response.error_message) ;
}