[英]ajax response data is undefined
我對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)
顯示為Undefined。
使用FireBug,我可以看到數據已正確返回。 為什么data.status為“未定義”?
如果您未在jQuery中指定$.ajax()
調用的dataType
字段,則會將響應的格式設置為純文本。 代碼的一種解決方法是將dataType: "JSON"
包含在$.ajax()
參數中,或者在success
函數中,使用以下方法將純文本響應解析為JSON對象:
data = JSON.parse(data); // You can now access the different fields of your JSON object
更新:
是的,我在操作URL中沒有
status
字段,如何在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);
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.