How to use a single jQuery function without importing the entire library?

Asked

Viewed 80 times

1

I’m making a extension for Firefox and in it I care about Jquery todinha. In the project I only use the function getJSON();.

I looked it up online and didn’t find much. I searched the github repositories and found some, but I don’t know if they are reliable or if there is a more viable solution.

So I was wondering if there’s any way to just import the function I use instead of the entire library, making my code much better.

  • 1

    You can search for solutions in javascript ("pure") equivalent to its functions that is used in jQuery

  • If the request method is GET You may be helped with this question: http://answall.com/questions/188577/como-obten-o-conte%C3%Bado-de-arquivo-javascript-na-forma-de-string/188834#188834

1 answer

4


The function jQuery.getJson() is a alias for an AJAX HTTP GET call, that is, you are only using the method ajax() from the library, so you are only using one asynchronous call and receiving a JSON as a response, correct?

To do the same without importing the entire library you can use XMLHttpRequest which is what the method jQuery.ajax() (and its derivative jQuery.getJSON()) uses, since the same is only a wrapper.

While with jQuery you would

$.ajax('service/user/1234', {
    method: 'POST',
    contentType: 'application/json',
    processData: false,
    data: JSON.stringify({
        name: 'João de Barros',
        age: 34
    })
})
.then(function success(userInfo) {
    // userInfo será um objeto contendo propriedades como nome, idade, 
    // endereço, etc.
});

With Xmlhttprequest you would do so

var xhr = new XMLHttpRequest();
xhr.open('POST', 'service/user/1234');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
    if (xhr.status === 200) {
        var userInfo = JSON.parse(xhr.responseText);
        // userInfo será o mesmo objeto contendo propriedades como nome, 
        // idade, endereço, etc.
    }
};
xhr.send(JSON.stringify({
    name: 'João de Barros',
    age: 34
}));

Ref.:

  • It worked! Thanks! Thanks for the links, they helped us understand. But I used the GET method. I have another problem regarding the formatting of the text. When I pick up the data before using Jsonparse, the text has /n/t, the original font formatting. But when I turn to JSON and print to DOM they disappear. They lose all formatting. You know something?

  • String value does not lose line breaks \n, \r\n and tabulations \t, These are escapes, but the JSON itself is serialized and minified (the formatting is removed). You are missing formatting a String that is a value within JSON or formatting JSON before turning it into an object?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.