gpt4 book ai didi

ajax - 使用 React.js 和 Ajax 在 Laravel 5 中显示验证错误

转载 作者:行者123 更新时间:2023-12-03 13:29:07 24 4
gpt4 key购买 nike

我正在运行一个 Laravel 5 应用程序,其主视图使用 React.js 渲染。在页面上,我有一个简单的输入表单,我正在使用 Ajax 处理该表单(在不刷新页面的情况下发回输入)。我验证 UserController 中的输入数据。我想做的是在我的 View 中显示错误消息(如果输入未通过验证)。

我还希望根据 React.js 代码中的状态(已提交或未提交)显示验证错误。

如何使用 React.js 而不刷新页面来做到这一点?

这是一些代码:

React.js 代码:

var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;

var SignupForm = React.createClass({
getInitialState: function() {
return {email: '', submitted: false, error: false};
},

_updateInputValue(e) {
this.setState({email: e.target.value});
},

render: function() {
var text = this.state.submitted ? 'Thank you! Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};
return (
<div>
{this.state.submitted ? null :
<div className="overall-input">
<ReactCSSTransitionGroup transitionName="example" transitionAppear={true}>
<input type="email" className="input_field" onChange={this._updateInputValue} ref="email" value={this.state.email} />

<div className="button-row">
<a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
</div>
</ReactCSSTransitionGroup>
</div>
}
</div>
)
},

saveAndContinue: function(e) {
e.preventDefault()

if(this.state.submitted==false) {
email = this.refs.email.getDOMNode().value
this.setState({email: email})
this.setState({submitted: !this.state.submitted});

request = $.ajax({
url: "/user",
type: "post",
data: 'email=' + email + '&_token={{ csrf_token() }}',
data: {'email': email, '_token': $('meta[name=_token]').attr('content')},
beforeSend: function(data){console.log(data);},
success:function(data){},
});


setTimeout(function(){
this.setState({submitted:false});
}.bind(this),5000);

}

}
});

React.render(<SignupForm/>, document.getElementById('content'));

用户 Controller :

public function store(Request $request) {

$this->validate($request, [
'email' => 'Required|Email|Min:2|Max:80'
]);

$email = $request->input('email');;

$user = new User;
$user->email = $email;
$user->save();

return $email;

}

感谢您的帮助!

最佳答案

根据 Laravel 文档,他们在验证失败时发送带有 422 代码的响应:

If the incoming request was an AJAX request, no redirect will be generated. Instead, an HTTP response with a 422 status code will be returned to the browser containing a JSON representation of the validation errors

因此,您只需要处理响应,如果验证失败,则向状态添加验证消息,如以下代码片段所示:

  request = $.ajax({ 
url: "/user",
type: "post",
data: 'email=' + email + '&_token={{ csrf_token() }}',
data: {'email': email, '_token': $('meta[name=_token]').attr('content')},
beforeSend: function(data){console.log(data);},
error: function(jqXhr, json, errorThrown) {
if(jqXhr.status === 422) {
//status means that this is a validation error, now we need to get messages from JSON
var errors = jqXhr.responseJSON;
var theMessageFromRequest = errors['email'].join('. ');
this.setState({
validationErrorMessage: theMessageFromRequest,
submitted: false
});
}
}.bind(this)
});

之后,在“render”方法中,只需检查 this.state.validationErrorMessage 是否已设置并将消息渲染到某处:

  render: function() {
var text = this.state.submitted ? 'Thank you! Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};
return (
<div>
{this.state.submitted ? null :
<div className="overall-input">
<ReactCSSTransitionGroup transitionName="example" transitionAppear={true}>
<input type="email" className="input_field" onChange={this._updateInputValue} ref="email" value={this.state.email} />
<div className="validation-message">{this.state.validationErrorMessage}</div>
<div className="button-row">
<a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
</div>
</ReactCSSTransitionGroup>
</div>
}
</div>
)
}

关于ajax - 使用 React.js 和 Ajax 在 Laravel 5 中显示验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31487641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com