Back to "एचएमएक्स के साथ एक स्मार्ट खोज छोड़ाName"

This is a viewer only at the moment see the article on how this works.

To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk

This is a preview from the server running through my markdig pipeline

HTMX Alpine.js

एचएमएक्स के साथ एक स्मार्ट खोज छोड़ाName

Monday, 16 September 2024

परिचय

एक पिछले पोस्ट में मैंने तुम्हें दिखाया है कि कैसे एक बनाने के लिए Ajjs और HMMX का उपयोग कर छोड़ दें तब मैंने दिखाया कि कैसे हम क्रॉस-साइट निवेदन को सक्षम कर सकते हैं के लिए driy सुरक्षा का उपयोग कर सकते हैं AntiforgeryRequestToken युयूपी. में जावास्क्रिप्ट के साथ नीक डोकेट होल कैश को चलाने के लिए HMX इस्तेमाल किया जा रहा है___ एक उल्लेखनीय मुद्दा था कि इसने कैसे पन्‍नों को हरा दिया ।

समस्या

यह मुद्दा था HMMAX AJAX लोड करने के लिए प्रयोग कर रहा था जब आप नीचे दिए गए पृष्ठ से परिणाम को चुन लिया था. यह केवल डीएडी काम किया.

  selectResult(result) {
            htmx.ajax('get', result.url, {
                target: '#contentcontainer',  // The container to update
                swap: 'innerHTML',            // Replace the content inside the target
            }).then(function() {
                history.pushState(null, '', result.url);
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            });

यह मुद्दा था कि जब यह सही पृष्ठ लोड करेगा तथा दिखाए गए यूआरएल को नए यूआरएल के साथ अद्यतन करेगा तो यह बैकअप बटन को उलटा कर देगा. जैसा कि पृष्ठ सही इतिहास में लोड नहीं किया गया था.

के रूप में मेरे साथ पीछे की ओर दिए गए आखिरी लेख में बताया गया है कि वह कौन है । यह मैं ठीक करना चाहता था कुछ था.

हल

इस समस्या को पहले के रूप में HMAX इसे सीधे संभालना था. यह करने के लिए मैं अपने टेम्पलेट को अद्यतन किया...... मैं खोज परिणाम के लिए उपयोग में.

_typeahead.cshtml

<div x-data="window.mostlylucid.typeahead()" class="relative" id="searchelement" x-on:click.outside="results = []">
    @Html.AntiForgeryToken()
    <label class="input input-sm bg-neutral-500 bg-opacity-10 input-bordered flex items-center gap-2">
        <input
            type="text"
            x-model="query"
            x-on:input.debounce.200ms="search"
            x-on:keydown.down.prevent="moveDown"
            x-on:keydown.up.prevent="moveUp"
            x-on:keydown.enter.prevent="selectHighlighted"
            placeholder="Search..."
            class="border-0 grow input-sm text-black dark:text-white bg-transparent w-full"/>
        <i class="bx bx-search"></i>
    </label>
    <!-- Dropdown -->
    <ul x-show="results.length > 0"
        id="searchresults"
        class="absolute z-100 my-2 w-full bg-white dark:bg-custom-dark-bg border border-1 text-black dark:text-white border-neutral-600 rounded-lg shadow-lg">
        <template x-for="(result, index) in results" :key="result.slug">
            <li :class="{
                'dark:bg-blue-dark bg-blue-light': index === highlightedIndex,
                'dark:hover:bg-blue-dark hover:bg-blue-light': true
            }"
                class="cursor-pointer text-sm p-2 m-2">
                <!-- These are the key changes.-->
                <a
                    x-on:click="selectResult(index)"
                    @* :href="result.url" *@
                    :hx-get="result.url"
                    hx-target="#contentcontainer"
                    hx-swap="innerHTML"
                    hx-push-url="true"
                    x-text="result.title"
                   >
                </a>
                <-- End of changes -->
            </li>
        </template>
    </ul>

</div>

आप मैं अब उत्पन्न होता है कि देखेंगे सही इस कोड ब्लॉक में HMMX लिंक. हमें सही HMAX बर्ताव का उपयोग करते हैं.

typeahead.js

इसे मेरे बैकएण्ड जावास्क्रिप्ट कोड में सक्षम करने के लिए मैंने निम्न को अपनी खोज विधि में जोड़ा (नीचे दिखाया). वह this.$nextTick इस देरी का निर्माण तब तक होता है जब तक कि ऊपर बताए उस टेम्पलेट को पूरा नहीं किया जा सकता ।

तब मैं उपयोग htmx.process() सर्च तत्व पर जो कि वांछित रूप में HMMX गुण काम सुनिश्चित करेगा.


.then(data => {
 this.results = data;
this.highlightedIndex = -1; // Reset index on new search
 this.$nextTick(() => {
    htmx.process(document.getElementById('searchresults'));
 });
})
typeahead.js search
   search() {
            if (this.query.length < 2) {
                this.results = [];
                this.highlightedIndex = -1;
                return;
            }
            let token = document.querySelector('#searchelement input[name="__RequestVerificationToken"]').value;
            console.log(token);
            fetch(`/api/search/${encodeURIComponent(this.query)}`, { // Fixed the backtick and closing bracket
                method: 'GET', // or 'POST' depending on your needs
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': token // Attach the AntiForgery token in the headers
                }
            })
                .then(response => {
                    if(response.ok){
                        return  response.json();
                    }
                    return Promise.reject(response);
                })
                .then(data => {
                    this.results = data;
                    this.highlightedIndex = -1; // Reset index on new search
                    this.$nextTick(() => {
                        htmx.process(document.getElementById('searchresults'));
                    });
                })
                .catch((response) => {
                    console.log(response.status, response.statusText);
                    if(response.status === 400)
                    {
                        console.log('Bad request, reloading page to try to fix it.');
                        window.location.reload();
                    }
                    response.json().then((json) => {
                        console.log(json);
                    })
                    console.log("Error fetching search results");
                });
        }
एक बार में एक पृष्ठ चुना गया है मैं कोड को पृष्ठ चुनने के लिए संभालता हूँ, लिंक पर क्लिक करें परिणाम (खोज बक्से को बन्द करने के लिए).
selectHighlighted() {
            if (this.highlightedIndex >= 0 && this.highlightedIndex < this.results.length) {
                this.selectResult(this.highlightedIndex);
                
            }
        },

        selectResult(selectedIndex) {
       let links = document.querySelectorAll('#searchresults a');
       links[selectedIndex].click();
            this.$nextTick(() => {
                this.results = []; // Clear the results
                this.highlightedIndex = -1; // Reset the highlighted index
                this.query = ''; // Clear the query
            });
        }

यह खोज परिणाम में लिंक के क्लिक से चयनित है.

 <a
  x-on:click="selectResult(index)"
  :hx-get="result.url"
  hx-target="#contentcontainer"
  hx-swap="innerHTML"
  hx-push-url="true"
  x-text="result.title"
  >
  </a>

कौन है जो पृष्ठ लोड करेगा और यूआरएल को ठीक से अद्यतन करेगा.

मैं माता-पिता बॉक्स में कोड भी है '% 1' आप तीर कुंजी का उपयोग करने और प्रवेश करने की अनुमति देता है.

    <label class="input input-sm bg-neutral-500 bg-opacity-10 input-bordered flex items-center gap-2">
        <input
            type="text"
            x-model="query"
            x-on:input.debounce.200ms="search"
            x-on:keydown.down.prevent="moveDown"
            x-on:keydown.up.prevent="moveUp"
            x-on:keydown.enter.prevent="selectHighlighted"
            placeholder="Search..."
            class="border-0 grow input-sm text-black dark:text-white bg-transparent w-full"/>
        <i class="bx bx-search"></i>
    </label>

आप देखेंगे कि यह सभी कोड है आप सिर्फ हिट करने के लिए सक्षम करने के लिए और चयनित पृष्ठ पर नेविगेट करें.

ऑन्टियम

खोज के प्रयोग से उपयोक्ता अनुभव को बढ़ाने के लिए मौजूदा खोज छोड़ देने के लिए मात्र एक शीघ्र अद्यतन लेख में एक त्वरित अद्यतन लेख दिया गया । एक बार फिर यह एक MIMIG उपयोगकर्ता परिवर्तन का सामना कर रहा है लेकिन सिर्फ उपयोगकर्ता अनुभव बढ़ा देता है; जो एक वेब डेवलपर के रूप में आपकी प्राथमिक चिंता है (सबसे अधिक भुगतान किया जा रहा है :)

logo

©2024 Scott Galloway