[英]How to access json data and use in if condition in following scenario?
Following is my AJAX function code: 以下是我的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();
});
Here in response following is the content coming from PHP. 作为回应,以下是来自PHP的内容。 This content is already converted into json format using the method
json_encode()
已经使用
json_encode()
方法将该内容转换为json格式
{
"error_message": "Id can't be blank<br>Please select Date<br>Image can't be blank<br>"
}
I want to check whether the array response[error_message] and if it's not empty then I want to show the content in alert box otherwise do nothing. 我想检查数组response [error_message]是否为空,然后要在警报框中显示内容,否则什么也不做。
Please help me in this regard. 请在这方面帮助我。
thanks in advance. 提前致谢。
Try this: 尝试这个:
<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>
Use : 采用 :
if ( response.hasOwnProperty('error_message') && '' != response.error_message ){
alert(response.error_message) ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.