反应ajax axios没有到达symfony控制器并返回模板

问题描述 投票:0回答:1

我正在尝试通过我的react + symfony应用程序中的ajax发送一些数据。没有错误,但ajax正在获取html模板而不是symfony函数响应。这是代码:

Symfony 3.4控制器功能:

/**
 * @Route("/loginPage", name="loginPage")
 */
public function loginAction(Request $request)
{
    if($request->request->get('username')){
        //make something curious, get some unbelieveable data
        $arrData = ['output' => 'here the result which will appear in div'];
        return new JsonResponse($arrData);
    }

    return new Response('success');

}

反应组件:

    import React, { Component } from 'react';
import { Form, Text } from 'react-form';
import axios from 'axios';


class Login extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleNameChange = this.handleNameChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.state = {
      name: '',
      password: ''
    }
  }

  handleSubmit(event) {
    event.preventDefault();
    axios.post(setData, {
      username: this.state.name,
      password: this.state.password
    })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

  }
  handleNameChange(e) {
  this.setState({name: e});
  }
  handlePasswordChange(e) {
    this.setState({password: e});
  }
  render() {
    return (
      <div className="card">
        <div className="card-block">
          <h4 className="card-title">Zaloguj się</h4>
          <div className="card-text">
            <Form>
              { formApi => (
                <form onSubmit={this.handleSubmit} id="form1">
                  <Text className="form-control" field="name" id="name" placeholder="Login" value={this.state.name} onChange={this.handleNameChange} required />
                  <Text className="form-control" field="password" type="password" id="password" placeholder="Hasło" value={this.state.password} onChange={this.handlePasswordChange} required />
                  <button className="btn btn-secondary" type="submit">Zaloguj się</button>
                </form>
              )}
            </Form>
          </div>
        </div>
      </div>
    );
  }
}
export default Login

这里是我得到的响应数据,这是我的twig模板的代码:Response

请帮忙 :)

php ajax reactjs symfony templates
1个回答
0
投票

解决方案是在symfony中添加route.yml文件的路由,例如:

loginPage:
path:  /homePage
defaults: {
    _controller: AppBundle:Default:index,
    }
requirements:
    _method:  POST
© www.soinside.com 2019 - 2024. All rights reserved.