0

我正在尝试使用 Javascript 获取选定的值并将该值发送到服务器端,以便使用 Laravel - PHP 处理它。这是我到目前为止写的 ocde,但我没有在服务器端得到它,还有什么我需要做的吗?

这是刀片文件:

{!! Form::open(array('url' => 'created-products', 'method' => 'post'), array('id'=>'createproduct')) !!}
{!! Form::token() !!}

    @if(!Auth::check())
        <p><h3>Please login to create product</h3></p>
        @else
            <p>{!! Form::select('companyname', array('' => 'Select a Company') + $listCompanies, null, array('id'=>'companynameId')) !!} </p>
            <p>{!! Form::text('productname', Input::old('productname')) !!}</p>
            <p>{!! Form::hidden('hiddenCompanyName', '', array('id'=>'selectedCompanyHidden')) !!}</p>
            <p>{!! Form::submit('CREATE PRODUCT') !!}</p>

    @endif

    <script>
        var returnedCompany = document.getElementById("companynameId");
        var storedCompany = returnedCompany.options[returnedCompany.selectedIndex].value;

        var hiddenCompanyId = document.getElementsByName('hiddenCompanyName');
        document.createproduct.hiddenCompanyId.value = storedCompany;
        document.forms["createproduct"].submit();
    </script>
{!! Form::close() !!}

这是从刀片文件中获取值的函数:

private static function compareCompany(ProductRequest $productRequest){
        $companyPicked = $productRequest->hiddenCompanyName;
        $listedCompanies = Company::where('user_id', '=', Auth::user()->id);
        $companies = new Company;
        if($companies->user_id === Auth::user()->id)
        {   
            foreach($listedCompanies as $company) {
                if($company->companyname === $companyPicked)
                {
                    return $company->id;
                } 
            }
        }
    }

这是将其保存到数据库中的功能。

public function store(ProductRequest $productRequest)
{
   $product = new Product;
    $company = new Company;
   if($productRequest->isMethod('post')){

   $product->user_id     = Auth::user()->id;
   $product->company_id  = $this->compareCompany($productRequest);
   $product->companyname = $productRequest->companyname;
   $product->productname = $productRequest->productname;

   $product->save();
   return redirect()->route('companyindex')->with('message', 'Your question has been posted.');
   }else{
        return redirect('company-create')->withErrors($productRequest)->withInput();
    }
}

请帮忙。这几天我一直在做这件事。欣赏。

4

1 回答 1

0

您现在拥有的代码将在您做任何事情之前提交表单,您应该添加onsubmit事件:

document.getElementById("createproduct").onsubmit=function(e)
{
    e.preventDefault();

    var returnedCompany = document.getElementById("companynameId");
    var storedCompany = returnedCompany.options[returnedCompany.selectedIndex].value;
    var hiddenCompanyId = document.getElementsByName('hiddenCompanyName')[0];

    document.createproduct.hiddenCompanyId.value = storedCompany;
    document.forms["createproduct"].submit();
};

希望这可以帮助。

于 2015-12-29T08:07:22.550 回答