我在此代码中使用ajax使用post方法获得了JSON请求
$(document).ready(function() {
$(document).on('submit', '#registration_check', function() {
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'apidomain.com',
data: data,
success: function(data) {
$("#registration_check").fadeOut(500).hide(function() {
$(".result_1").fadeIn(500).show(function() {
$(".result_1").html(data);
});
});
}
});
return false;
});
});
响应将在此元素上返回3个字段,如姓名,电子邮件,电话:
<div id="result_1"></div>
它到目前为止工作得很好,但是我想要做的是我想显示警报或弹出消息,如果ajax响应发现一些返回值为null。例如:
弹出或警报将出现,文本电话号码为空。
我想到的第一件事是:你是否需要在文档元素中使用JSON响应,或者是,你不知道如何使用jQuery Ajax?
无论如何,这个解决方案应该在两种情况下帮助你:
$(document).ready(function()
{
$(document).on('submit', '#registration_check', function()
{
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'apidomain.com',
data : data,
dataType: 'json', // tell jQuery, that the response data will be a JSON - it will be parsed automatically
success : function(data)
{
// now you have a parsed JSON object in the 'data' var
var show_alert = false;
if (data.phone === null || !data.phone.length) {
show_alert = true;
}
if (data.email === null || !data.email.length) {
show_alert = true;
}
if (show_alert) {
alert('here is the alert :)');
}
$("#registration_check").fadeOut(500).hide(function()
{
$(".result_1").fadeIn(500).show(function()
{
$(".result_1").html(JSON.stringify(data));
});
});
}
});
return false;
});
});
如果您的数据是JSON对象,那么您可以执行以下操作:
success: function(data) {
for (var i in data) {
if (!data[i]) {
alert(/* MESSAGE HERE */)
return;
}
}
// Your regular code here
}
您可以在php文件中创建值的关联数组,并以json格式回显它
echo json_encode($array);
然后你会在这样的ajax响应中收到这个
var objs = JSON.parse(data);
然后你可以通过像你在php文件中的关联数组中定义的name
,email
和phone
这样的键来解析值
console.log(objs.name);
console.log(objs.email);
console.log(objs.phone);
这是您可以单独解析值的方法。您也可以按自己的方式申请条件