Javascript переменная get запроса

JavaScript: как получить get параметр

Как получить get параметры

В javascript нет встроенных функций, которые позволяют получить значение определенного get параметра. Но мы можем написать свою функцию которая будет искать и возвращать значение нужного нам get параметра.

Функция для получения get:

Функция работает аналогично функции $_GET в PHP. Распознает массивы в гет параметрах.

function $_GET(keys) { function getElement(arr, keys) { let key = keys.shift(); return keys.length ? getElement(arrJavascript переменная get запроса, keys) : arrJavascript переменная get запроса; } function setElement(arr, keys, value) { let key = keys.shift(); if (keys.length) { arrJavascript переменная get запроса = {}; setElement(arrJavascript переменная get запроса, keys, value) } else { if (!key) { key = 0; while (key in arr) { key++; } } arrJavascript переменная get запроса = value; } } let get = {}; window.location.search.slice(1).split('&').forEach(function(item) { let data = item.split('='); let key = data[0].replace(/\[.*/, ''); let value = data[1] ? data[1] : ''; if (data[0] !== key) { let subkeys = data[0].match(/(?<=\[).*?(?=\])/g); getJavascript переменная get запроса = getJavascript переменная get запроса ? getJavascript переменная get запроса : {}; setElement(getJavascript переменная get запроса, subkeys, value); } else { getJavascript переменная get запроса = value; } }); if (keys) { return getElement(get, keys.constructor !== Array ? keys.split() : keys); } return get; }

Получение всеx get параметров в виде объекта: $_GET()
Получение значения get параметра: $_GET('param')
Получение значения get параметра массива, нужно указать вложенность в виде массива: $_GET(['param', 'key'])

Читайте также:  From html to jsf

Простая функция для получения get:

Данная функция позволяет получить значение определенного get параметра точно по ключу, массивы не распознает.

function $_GET(key) { var p = window.location.search; p = p.match(new RegExp(key + '=([^&=]+)')); return p ? p[1] : false; }

Например, ваш url из которого нужно получить get выглядит так: http://frontblog.ru/index.php?page=1

Для того чтобы получить значение параметра page вставляете в свой скрипт $_GET('page') и данная функция вернет вам 1 , что является значение параметра page .

Если параметра page не окажется на странице, то функция $_GET('page') вернет false .

Функция для получения всех get параметров в виде массива:

Рассмотренная выше функция позволяет получить определенный параметр по ключу, но можно получить все параметры сразу и записать их в переменную и далее использовать их как душе угодно, массивы эта функция не распознает. Пример такой функции:

var gets = (function() { var a = window.location.search; var b = new Object(); a = a.substring(1).split("&"); for (var i = 0; i < a.length; i++) { c = a[i].split("="); b[c[0]] = c[1]; } return b; })();

Данная функция получает все get параметры и записывает их в переменную gets . Для получения параметра page нужно написать так gets['page'] . Плюс такого способа только в том, что функция выполнится один раз и у вас будут все параметры в виде ассоциативного массива.

Например, для url http://frontblog.ru/index.php?page=1&item=2 массив будет выглядеть так:

var gets = { "page" : "1", "item" : "2" }

Ключами являются page и item . По ним и происходит поиск нужного значения: gets['page'] вернет 1 , gets['item'] вернет 2 .

Какой функцией воспользоваться решать вам. Также буду рад предложениям подобных функций в комментариях.

Источник

JavaScript Get Request – How to Make an HTTP Request in JS

Joel Olawanle

Joel Olawanle

JavaScript Get Request – How to Make an HTTP Request in JS

When building applications, you will have to interact between the backend and frontend to get, store, and manipulate data.

This interaction between your frontend application and the backend server is possible through HTTP requests.

There are five popular HTTP methods you can use to make requests and interact with your servers. One HTTP method is the GET method, which can retrieve data from your server.

This article will teach you how to request data from your servers by making a GET request. You will learn the popular methods that exist currently and some other alternative methods.

For this guide, we'll retrieve posts from the free JSON Placeholder posts API.

There are two popular methods you can easily use to make HTTP requests in JavaScript. These are the Fetch API and Axios.

How to Make a GET Request with the Fetch API

The Fetch API is a built-in JavaScript method for retrieving resources and interacting with your backend server or an API endpoint. Fetch API is built-in and does not require installation into your project.

Fetch API accepts one mandatory argument: the API endpoint/URL. This method also accepts an option argument, which is an optional object when making a GET request because it is the default request.

Let’s create a GET request to get a post from the JSON Placeholder posts API.

fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) .then((json) => console.log(json)); 

This will return a single post which you can now store in a variable and use within your project.

Note: For other methods, such as POST and DELETE, you need to attach the method to the options array.

How to Make a GET Request with Axios

Axios is an HTTP client library. This library is based on promises that simplify sending asynchronous HTTP requests to REST endpoints. We will send a GET request to the JSONPlaceholder Posts API endpoint.

Axios, unlike the Fetch API, is not built-in. This means you need to install Axios into your JavaScript project.

To install a dependency into your JavaScript project, you will first initialize a new npm project by running the following command in your terminal:

And now you can install Axios to your project by running the following command:

Once Axios is successfully installed, you can create your GET request. This is quite similar to the Fetch API request. You will pass the API endpoint/URL to the get() method, which will return a promise. You can then handle the promise with the .then() and .catch() methods.

axios.get("https://jsonplaceholder.typicode.com/posts/1") .then((response) => console.log(response.data)) .catch((error) => console.log(error)); 

Note: The major difference is that, for Fetch API, you first convert the data to JSON, while Axios returns your data directly as JSON data.

At this point, you have learned how to make a GET HTTP request with Fetch API and Axios. But there are some other methods that still exist. Some of these methods are XMLHttpRequest and jQuery.

How to Make a GET Request with XMLHttpRequest

You can use the XMLHttpRequest object to interact with servers. This method can request data from a web server’s API endpoint/URL without doing a full page refresh.

Note: All modern browsers have a built-in XMLHttpRequest object to request data from a server.

Let’s perform the same request with the XMLHttpRequest by creating a new XMLHttpRequest object. You will then open a connection by specifying the request type and endpoint (the URL of the server), then you'll send the request, and finally listen to the server’s response.

const xhr = new XMLHttpRequest(); xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1"); xhr.send(); xhr.responseType = "json"; xhr.onload = () => < if (xhr.readyState == 4 && xhr.status == 200) < console.log(xhr.response); >else < console.log(`Error: $`); > >; 

In the above code, a new XMLHttpRequest object is created and stored in a variable called xhr . You can now access all its objects using the variable, such as the .open() method, when you specify the request type (GET) and the endpoint/URL where you want to request data.

Another method you will use is .send() , which sends the request to the server. You can also specify the format in which the data will be returned using the responseType method. At this point, the GET request is sent, and all you have to do is listen to its response using the onload event listener.

If the client's state is done (4), and the status code is successful (200), then the data will be logged to the console. Otherwise, an error message showing the error status will appear.

How to Make a GET Request with jQuery

Making HTTP requests in jQuery is relatively straightforward and similar to the Fetch API and Axios. To make a GET request, you will first install jQuery or make use of its CDN in your project:

With jQuery, you can access the GET method $.get() , which takes in two parameters, the API endpoint/URL and a callback function that runs when the request is successful.

$.get("https://jsonplaceholder.typicode.com/posts/1", (data, status) => < console.log(data); >); 

Note: In the callback function, you have access to the request's data and the request's status.

You can also use the jQuery AJAX Method, which is quite different and can be used to make asynchronous requests:

Wrapping Up

In this article, you have learned how to make the HTTP GET request in JavaScript. You might now begin to think — which method should I use?

If it’s a new project, you can choose between the Fetch API and Axios. Also, if you want to consume basic APIs for a small project, there is no need to use Axios, which demands installing a library.

Источник

Как сохранить результат GET запроса в переменную на JS?

С помощью XMLHttpRequest осуществляю GET запрос. Потом устанавливаю onreadystatechange и на readyState == 4 вывожу результат. Можно ли как-то проверить readyState без onreadystatechange и сохранить результат в переменную, чтобы потом использовать в любой части кода?

ThunderCat

KorniloFF

BRAGA96

function ajax(params) < var request = new XMLHttpRequest(); request.open(params.type, params.url, params.async ? params.async : true); request.onload = function() < if (request.status >= 200 && request.status < 400) < // Успешный запрос if (params.success) params.success(request.responseText); >else < // Запрос дошел до сервера, но вернул ошибку if (params.error) params.error(request, request.status); >>; request.onerror = function() < // Ошибка запроса if (params.error) params.error(request, request.status); >; request.setRequestHeader('Content-Type', params.contentType ? params.contentType : 'application/x-www-form-urlencoded; charset=UTF-8'); request.send(params.data); >

Вызов функции. В колбеке success делаем с ответом что хотим. Не забывайте, что XHR запросы происходят асинхронно.

ajax(< type: 'GET', url: 'https://jsonplaceholder.typicode.com/posts', contentType: 'application/json; charset=UTF-8', data: < key: 'prop' >, async: true, success: function(response) < console.log(response); >, error: function(xhr, status) < console.log(xhr, status); >>);

Источник

Оцените статью