Fetch vs. AjaxCall

前端 未结 2 948
说谎
说谎 2021-01-29 23:50

What is the difference between typical AJAX and Fetch API?

Consider this scenario:

function ajaxCall(url) {
  return new Promise(function(resolve, reject         


        
相关标签:
2条回答
  • 2021-01-30 00:05

    Your ajaxCall is returning the responseText from the XMLHttpRequest object. It is filtering it out.

    You need to read the response Text in the fetch code.

    fetch('/foo/').then(x => x.text()).then(console.log)
    

    You can also use x.json() or x.blob()

    0 讨论(0)
  • 2021-01-30 00:15

    The Fetch API has built in methods for different datatypes.
    For just regular text/html you'd use the text() method, which returns a promise as well, and chain it with another then call.

    fetch('www.testSite').then( x => { 
        return x.text();
    }).then( y => {
        console.log(y);
    });
    

    The built-ins for the returned content is as follows

    • clone() - Creates a clone of a Response object.
    • error() - Returns a new Response object associated with a network error.
    • redirect() - Creates a new response with a different URL.
    • arrayBuffer() - Returns a promise that resolves with an ArrayBuffer.
    • blob() - Returns a promise that resolves with a Blob.
    • formData() - Returns a promise that resolves with a FormData object.
    • json() - Returns a promise that resolves with a JSON object.
    • text() - Returns a promise that resolves with a USVString (text).

    It also allows you to send things to the server, or add your own headers etc.

    fetch('www.testSite', {
        method  : 'post',
        headers : new Headers({
            'Content-Type': 'application/x-www-form-urlencoded'
        }),
        body    : new FormData(document.getElementById('myform'))
    }).then( response => {
        return response.json(); // server returned valid JSON
    }).then( parsed_result => {
        console.log(parsed_result);
    });
    
    0 讨论(0)
提交回复
热议问题