代码之家  ›  专栏  ›  技术社区  ›  Philipp Kishkovarov

将数据从Ajax发送到Laravel控制器。沃伊斯

  •  0
  • Philipp Kishkovarov  · 技术社区  · 7 年前

    我有一点不明白,因为我对发展很陌生。 我正在从多步骤表单收集数据,并希望在我的控件上的一个Ajax请求中处理所有表单输入。我做得很成功,但不知道如何使用 $request 如果它是来自Ajax的数组。 我可以用它 $request->input('name') 但在我的情况下,我需要像 $request->input('firstGrant.issue_date') 因为我的数据格式。请告诉我往哪边挖。

    我的方法是:

    submitCompany() {
     axios.post('/onboarding', {
        name: this.step1.name,
        type: this.step1.type,
        shares_amount: this.step2.shares_amount,
        par_value: this.step2.par_value,
        firstGrant: {
            issue_date: this.step3.firstGrant.issue_date,
            certificate: this.step3.firstGrant.certificate,
            share_price: this.step3.firstGrant.share_price,
            shares_amount: this.step3.firstGrant.shares_amount
        }
    
    })
    .then(function (response) {
        console.log(response);
        alert('Information saved!');
    })
    .catch(function (error) {
        console.log(error);
        alert('Wrong!');
    });
    }
    

    我的控制器:

    public function store(Request $request)
    {
        $userId = Auth::user()->id;
        $issueDate = $request->input('firstGrant.issue_date'); //How to do it right way?
        $certificate = $request->input('firstGrant.certificate');//How to do it right way? 
        $sharePrice = $request->input('firstGrant.share_price');//How to do it right way?
        $sharesAmount = $request->input('firstGrant.shares_amount');//How to do it right way?
    
        $equityGrant = EquityGrant::create([
            'user_id' => $userId,
            'share_id' => 91,
            'vesting' => 0,
            'status' => 'active',
            'issue_date' => $issueDate,
            'certificate' => $certificate,
            'share_price' => $sharePrice,
            'shares_amount' => $sharesAmount,
        ]); }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   JJWesterkamp    7 年前

    您可能需要配置AXIOS来发送一个头部以及每个请求,这些请求将使Laravel识别请求为XHR。一旦成功, $request->input('x.y') 陈述应该有效。

    Object.assign(axios.defaults.headers, {
        'X-Requested-With': 'XMLHttpRequest',
    });
    

    如果这仍然不起作用,您可能还需要检查AXIOS是否正确。 includes the CSRF-token 在请求头中。