بضعة أمثلة على إرسال طلب إلى الخادم

يوم جيد يا اصدقاء!

عند تطوير تطبيقات الويب ، غالبًا ما يكون من الضروري الحصول على البيانات من الخادم.

هناك العديد من الطرق للقيام بذلك في JavaScript اليوم.

دعونا نرى كيف يتم استخدام XMLHttpRequest و Fetch و Axios في الممارسة.

ستستخدم المهام JSONPlaceholder - واجهة برمجة تطبيقات وهمية REST API عبر الإنترنت للاختبار والنماذج الأولية (وبعبارة أخرى ، قاعدة بيانات للتدريب).

XMLHttpRequest


المهمة: احصل على قائمة المستخدمين وعرض هذه القائمة في وحدة التحكم.

القرار:

//   XMLHttpRequest   
let xhr = new XMLHttpRequest()

//  
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users')

//  
xhr.send()

/*xhr.onload = function() {
    if (xhr.status != 200) {
        console.log(`error ${xhr.status}:${xhr.statusText}`)
    } else {
        console.table(JSON.parse(xhr.response))
    }
}*/

//  
//   ,    
//  ,       
xhr.onload = () => xhr.status != 200 ? console.error(xhr.status) : console.table(JSON.parse(xhr.response))

//   
//     Content-Length,     
//   ,     
xhr.onprogress = event => {
    if (event.lengthComputable) {
        console.dir(`received ${event.loaded} of ${event.total} bytes`)
    } else {
        console.dir(`received ${event.loaded} bytes`)
    }
}

//   
xhr.onerror = () => console.error('error')

النتيجة:



كود على GitHub .

جلب


المهمة: مماثلة.

الحل (مقارنة مع XMLHttpRequest):

fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(json => console.table(json))
    .catch(error => console.error(error))

النتيجة:



كود على GitHub .

أو إذا كنت ترغب في عدم التزامن / في انتظار المزيد:

(async () => {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/users')
        const data = await response.json()
        console.table(data)
    } catch (error) {
        console.error(error)
    } finally {
        console.log('done')
    }
})()

النتيجة:



كود على GitHub .

دعنا نعقد المهمة قليلاً: الآن تحتاج إلى الحصول على صور من الخادم وتشكيل معرض منها.

القرار:

const url = 'https://jsonplaceholder.typicode.com/photos/'

getPhotosAndMakeGallery(url)

function getPhotosAndMakeGallery(url) {
    for (let i = 1; i < 11; i++) {
        fetch(url + i)
            .then(response => response.json())
            .then(photo => {
                let img = document.createElement('img')
                img.src = photo.url
                document.body.append(img)
            })
    }
}

النتيجة:



كود على GitHub .

أكسيوس


لتوصيل هذه المكتبة ، تحتاج إلى إضافة <script src = " unpkg.com/axios/dist/axios.min.js "> </script> في رأس المستند.

المهمة: احصل على قائمة المستخدمين واعرضها في وحدة التحكم.

القرار:

axios.get('https://jsonplaceholder.typicode.com/users')
    .then(response => console.table(response.data))
    .catch(error => console.log(error))

كود جيثب .

أو إذا كنت تفضل عدم المزامنة / الانتظار:

(async () => {
    try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/users');
        console.table(response.data);
    } catch (error) {
        console.error(error);
    }
})()

كود جيثب .

نحن نعقد المهمة: احصل على المهام وقم بإنشاء قائمة.

القرار:

const url = 'https://jsonplaceholder.typicode.com/todos/'

getTodosAndMakeList()

function getTodosAndMakeList() {
    const ul = document.createElement('ul')
    document.body.append(ul)

    for (let i = 1; i < 21; i++) {
        axios.get(url + i)
            .then(response => {
                let li = document.createElement('li')
                li.textContent = `title: ${response.data.title}; completed: ${response.data.completed}`
                ul.append(li)
            })
            .catch(error => console.log(error))
    }
}

النتيجة:



كود على GitHub .

نحن نعقدها: احصل على المستخدمين والتعليقات والصور ، ودمج هذه البيانات وتقديم كل شيء في شكل قابل للقراءة.

القرار:

function getUsers(i) {
    return axios.get('https://jsonplaceholder.typicode.com/users/' + i)
}

function getComments(i) {
    return axios.get('https://jsonplaceholder.typicode.com/comments/' + i)
}

function getPhotos(i) {
    return axios.get('https://jsonplaceholder.typicode.com/photos/' + i)
}

(async() => {
    for (let i = 1; i < 7; i++) {
        let request = await axios.all([getUsers(i), getComments(i), getPhotos(i)])
            .then(axios.spread(function(user, comment, photo) {
                let figure = document.createElement('figure')
                document.body.append(figure)
                let figcaption = document.createElement('figcaption')
                figcaption.textContent = `Post ${i}`
                figure.append(figcaption)

                let img = document.createElement('img')
                img.src = photo.data.url
                figure.append(img)

                let userName = document.createElement('p')
                userName.innerHTML = `<span>Name:</span> ${user.data.username}`
                figure.append(userName)

                let userComment = document.createElement('p')
                userComment.innerHTML = `<span>Comment:</span> ${comment.data.body}`
                figure.append(userComment)
            }))
    }
})()

النتيجة:



كود على GitHub .

شكرآ لك على أهتمامك.

All Articles