我对ajax帖子的提交有问题,这里是我的脚本
function postad(actionurl) {
if (requestRunning) return false ;
if (! $("#editadform").valid()) {
validator.focusInvalid();
return false ;
}
$('#ajxsave').show() ;
requestRunning = true ;
var postData = $('#editadform').serializeArray();
$.ajax(
{
url : actionurl,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$('#diverrors').html(data.errors) ;
$('#divalerts').html(data.alerts) ;
if (data.status=='success') { alert(data.status);
$('#siteid').val(data.siteid) ;
if ($('#adimager').val())
$('#divlmsg').html(data.alertimage) ;
$('#editadform').submit() ;
} else {
$('#ajxsave').hide() ;
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('#ajxsave').hide() ;
},
complete: function() {
requestRunning = false;
}
});
$('.btn').blur() // remove focus
return false ;
}
这适用于if (textStatus=='success') {
但是,当操作失败时,alert(data.status)
将显示未定义。
使用FireBug,我可以看到数据是正确返回的。那么,为什么data.status“未定义”呢?
发布于 2017-05-21 09:26:15
如果没有在dataType
中指定$.ajax()
调用的jQuery字段,则将响应格式化为纯文本。您的代码的解决方法是将dataType: "JSON"
包含到$.ajax()
参数中,或者在success
函数中使用以下方法将纯文本响应解析为JSON对象:
data = JSON.parse(data); // You can now access the different fields of your JSON object
更新:
是的,我没有
status
字段的操作url,如何在php代码中添加数据状态字段?
在创建用于返回JSON数据的PHP脚本时,首先需要构建一个数组,然后将其编码为JSON。
因此,假设您有一个PHP脚本,它成功并生成一些数据,然后放入一个$data
变量中,或者失败,那么可以采用以下样式:
<?php
// ^^ Do your PHP processing here
if($success) { // Your PHP script was successful?
$response = array("status" => "success!", "response" => $data);
echo json_encode($response);
}
else {
$reponse = array("status" => "fail", "message" => "something went wrong...");
echo json_encode($response);
}
?>
https://stackoverflow.com/questions/44095175
复制相似问题