我正在使用jQuery $ .ajax的ajax函数,这个函数成功调用另一个使用getJSON来检索数据的函数,但是当我使用dataType:' JSON'使用$ .ajax函数,不执行第二个函数。这种行为是正常的还是我做错了什么。
让我给你代码:: 第一个功能:
$('#someButton').on('click', function(){
$.ajax({
url: uploadURI,
type: 'post',
data: formData,
dataType: 'JSON', //when I add this line second function stopped working, I need this to do some checks.
processData: false,
contentType: false,
success: function() {
listFilesOnServer();
}
})
});
第二个函数::
function listFilesOnServer () {
var items = [];
$.getJSON(uploadURI, function(data) {
$.each(data, function(index, element) {
items.push('<li class="list-group-item">' + element + '<div class="pull-right"><a href="#" data-file="' + element + '" class="remove-file"><i class="glyphicon glyphicon-remove"></i></a></div></li>');
});
$('.list-group').html("").html(items.join(""));
});
}
对于第一个函数的服务器端代码(PHP),我想使用json_encode函数,但这种行为阻止了我。这是正常的还是解决方法。
答案 0 :(得分:0)
将contentType:'multipart / form-data'放入,而不是false。 删除ProcessData(在ajax中可选) 以JSON格式发送数据,例如:data:{Form:formData},
答案 1 :(得分:0)
$('#someButton').on('click', function(){
$.ajax({
url: uploadURI,
type: 'POST',
data: formData,
dataType: 'json', //When you using this, that mean you want the php to return JSON format too
success: function() { //If the result from PHP can't be parsed, the success function will not be triggered
listFilesOnServer();
},
error: function() { //The request completed.. but..
alert('Returned data has an error!');
listFilesOnServer(); //Do the second function here..
}
})
});
// Make sure you have add this line before echo the json data in PHP script
header('Content-type: application/json');
替代检查:
//remove -> dataType: 'json'
success: function(data) {
//alert(data);
try {
JSON.parse(data);
} catch(e){
alert('Data is not a raw JSON');
return;
}
//The data was a json, continuing to second function
listFilesOnServer();
}