Ajax在下拉列表中加载数据选择

时间:2016-08-11 09:00:17

标签: javascript php ajax laravel-5

我的观点中有一个下拉列表。当我在下拉列表中选择一个项目时,应加载ajax。因此,有一个表位置,它与联系人有一对多的关系。

因此,当我从位置下拉列表中选择一个位置时,应该加载与之对应的联系人。但它没有发生。

控制器:

public function location_contacts()
{
    $contacts = Contact::all();
    return view('partials.bookavisit_contact')->with(['contacts' => $contacts]);
}

位置下拉列表:

<div class="inline-control location-icon dropdown-icon">
    <select class="form-control" name="visit-location" id="visitLocation" onChange="getContact(value);" >
        <option date-person="lorem impsum" date-mail="lorem.ipsum@gmail.com" >Select Location</option>
        @foreach($locations as $location)
        <option date-person="lorem impsum" date-mail="lorem.ipsum@gmail.com" value="{!! $location->id !!}" >{!! $location->address !!}, {!! $location->city !!}, {!! $location->state !!}</option>
        @endforeach
    </select>
</div>

脚本:

@section('scripts')
<script type="text/javascript">

    function getContact(val) {

        var ajaxUrl = "/location_contacts";
        $.ajax({
            type: "POST",
            url: ajaxUrl,
            data:'location_id='+val,
            success: function(data){
                $("#contact").html(data);
            }
        });
    }
</script>
@endsection

部分联系人:

<div id="location-contact-info">
    <div class="content-head" id="contact">
        <h5  class="wow fadeInUp">Lorem ipsum</h5>
    </div>
    @foreach($contacts as $contact)
    <div class="contact-info-group row">
        <div class="contact-label">Contact Person:
            <span id="location-contact-name">{{$contact->first_name}} {{$contact->last_name}}</span>
        </div>
    </div>
    <div class="contact-info-group row">
        <div class="contact-label">Email:
            <span id="location-contact-mail" ><a href="mailto:{{$contact->email}}">{{$contact->email}}</a></span>
        </div>
    </div>
    @endforeach
</div>

1 个答案:

答案 0 :(得分:0)

您的 html 中存在错误,您的ID contact在您的部分内容,并且需要在您的主视图中显示如下:

<div class="inline-control location-icon dropdown-icon">
    <select class="form-control" name="visit-location" id="visitLocation" onChange="getContact(value);" >
        <option date-person="lorem impsum" date-mail="lorem.ipsum@gmail.com" >Select Location</option>
        @foreach($locations as $location)
        <option date-person="lorem impsum" date-mail="lorem.ipsum@gmail.com" value="{!! $location->id !!}" >{!! $location->address !!}, {!! $location->city !!}, {!! $location->state !!}</option>
        @endforeach
    </select>
</div>
<div id="contact"></div>

因此$("#contact").html(data);无效。

尝试一下。

此致