weixin_33696822 2019-12-26 22:09 采纳率: 0%
浏览 363

Ajax请求的动态URL

I'm trying to create a search field on the top navbar with ajax. Since it's on the navbar, it has to be present on all pages, therefore the URL is constantly changing.

$.ajax({
            type: 'GET',
            url: CURRENT_URL,
            dataType: 'json',
            data: {
                search: userSearch
            },
            success: function (){...

I'm working with Laravel, so i tried this on the navbar page:

<script>
            var CURRENT_URL = "{{url()->current()}}"
</script>

The CURRENT_URL is displayed fine if i try to console log it, but ajax gives an error "Source map error: Error: request failed with status 404". How can i insert the current URL into the ajax request?

  • 写回答

2条回答 默认 最新

  • weixin_33735676 2019-12-27 02:23
    关注

    Hopefully, this can help. Here's my approach to make my url dynamically I get the URL in every forms var URL = $('#example_form').prop('action'); then the URL variable must append or set via Js/Jquery. check my example below.

    <script type="text/javascript">
    var URL = $('#example_form').prop('action');
    $.ajax({
          type:'GET',
          url: URL+'/clearContent',
          beforeSend: function (xhr) {
            var TOKEN = $('meta[name="csrf-token"]').attr('content');
            if (TOKEN) {
              return xhr.setRequestHeader('X-CSRF-TOKEN', TOKEN);
            }
          },
          data:{
            get_category_id : $('.parent-id').val(),
          },
          success:function(data){
            if (data.response.status == true) {
              // your codes here
            }
          }, 
          dataType: 'json',
          complete: function () {}
        });
    
    评论

报告相同问题?