我有一个web程序将返回一个json,例如:{“name”:[“name name is required。”]},这是错误信息,预计会通过以下jquery发出警报.fail部分中的脚本,但.fail部分从未到达
$(function() {
$('textarea').summernote({height: 250});
$('form').submit(function(event) {
event.preventDefault();
var form = $(this);
if (form.attr('id') == '' || form.attr('id') != 'fupload'){
$.ajax({
type : form.attr('method'),
url : form.attr('action'),
data : form.serialize()
}).success(function() {
setTimeout(function() {
parent.$.colorbox.close();
//window.parent.location.reload();
}, 10);
}).fail(function(jqXHR, textStatus, errorThrown) {
// Optionally alert the user of an error here...
var textResponse = jqXHR.responseText;
var alertText = "One of the following conditions is not met:\n\n";
var jsonResponse = jQuery.parseJSON(textResponse);
$.each(jsonResponse, function(n, elem) {
alertText = alertText + elem + "\n";
});
alert('test1');
alert(alertText);
});
}
else{
alert('test1.5');
var formData = new FormData(this);
$.ajax({
type : form.attr('method'),
url : form.attr('action'),
data : formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false
}).success(function() {
alert('test1.6');
setTimeout(function() {
parent.$.colorbox.close();
//window.parent.location.reload();
}, 10);
}).fail(function(jqXHR, textStatus, errorThrown) {
// Optionally alert the user of an error here...
var textResponse = jqXHR.responseText;
var alertText = "One of the following conditions is not met:\n\n";
var jsonResponse = jQuery.parseJSON(textResponse);
$.each(jsonResponse, function(n, elem) {
alertText = alertText + elem + "\n";
});
alert('test2');
alert(alertText);
});
};
});
$('.close_popup').click(function() {
parent.$.colorbox.close()
//window.parent.location.reload();
});
});
每个人都知道使上述脚本工作需要什么?
------ -------更新 后端是laravel,因为我不想使用自定义请求类
public function postEdit(Request $request, $id)
{
$input = $request->all();
$name = $input['name'];
$rules = array('name' => 'required|max:255');
$message = array('name.required' => 'The :attribute field is required.');
$validator = Validator::make($input, $rules, $message);
if ($validator->fails()) {
return $validator->messages()->toJson();
}
}
如果我使用自定义请求类,它将返回422(不可处理的实体)
<?php namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class VendorRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required',
];
}
}