代码之家  ›  专栏  ›  技术社区  ›  cysieek

react ajax axios未到达symfony控制器并返回模板

  •  0
  • cysieek  · 技术社区  · 8 年前

    我正在尝试在我的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
    

    下面是我得到的响应数据,这是我的小树枝模板的代码: Response

    请帮助:)

    1 回复  |  直到 8 年前
        1
  •  0
  •   cysieek    8 年前

    解决方案是将路由添加到路由。symfony中的yml文件,例如:

    loginPage:
    path:  /homePage
    defaults: {
        _controller: AppBundle:Default:index,
        }
    requirements:
        _method:  POST
    
    推荐文章