Yêu cầu thg 10 17, 2022 1:40 SA 374 0 1
  • 374 0 1
0

Error Uncaught TypeError: Failed to construct 'URL': Invalid URL By a[href="//...]

Chia sẻ
  • 374 0 1

Sử dụng Trim URLs biến https:// hoặc http:// thành // thì gặp phải lỗi javascipt : Uncaught TypeError: Failed to construct 'URL': Invalid URL

Mặc định mã trong javascript :

$(document).on('click', '#ajax-filters-form .pagination a', function (e) {
            e.preventDefault();
            var url = new URL($(e.currentTarget).attr('href'));
            var page = url.searchParams.get('page');
            $('#ajax-filters-form input[name=page]').val(page)
            $('#ajax-filters-form').trigger('submit');
		});

Còn nội dung html :

<ul class="pagination">
    <li aria-disabled="true" aria-label="« Previous" class="page-item disabled"><span aria-hidden="true" class="page-link">‹</span>
    </li>
    <li aria-current="page" class="page-item active"><span class="page-link">1</span>
    </li>
    <li class="page-item"><a href="//domain.com?page=2" class="page-link">2</a>
    </li>
    <li class="page-item"><a href="//domain.com?page=2" rel="next" aria-label="Next »" class="page-link">›</a>
    </li>
</ul>

Click mouse page 2 thì gặp lỗi : Uncaught TypeError: Failed to construct 'URL': Invalid URL

Nếu tắt Trim URLs thì link thế này sẽ không lỗi < a href="https://domain.com?page=2"

Mong A/E giúp đỡ. Xin cảm ơn

1 CÂU TRẢ LỜI


Đã trả lời thg 10 17, 2022 2:24 SA
Đã được chấp nhận
0

method new URL thì đầu vào là 1 string với format là 1 url => bạn nên đọc document (https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) của menthod đó.

Mình nghĩ khi click thì url get được ko phải là 1 chuỗi với format của 1 url. thử code lại xem. new URL(url, window.location.origin)

Chia sẻ
Avatar MacKen @MacKen
thg 10 22, 2022 7:17 SA

Theo bạn : new URL(url, window.location.origin) mọi thứ ổn . Thanks

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí