- js-http-build-query
- Installation:
- Usage:
- Contributing
- Security Vulnerabilities
- License
- Курсы javascript
- Отправить комментарий
- Учебник javascript
- Основные элементы языка
- Сундучок с инструментами
- Интерфейсы
- Все об AJAX
- Оптимизация
- Разное
- Saved searches
- Use saved searches to filter your results more quickly
- License
- muhaimenul/js-http-build-query
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- PHP’s http_build_query in JavaScript
- How to use
- A community effort
- Notes
- Examples
js-http-build-query
A simple JavaScript package to generate URL-encoded HTTP Query String. Just create a object using query parameters and their values, and pass the object through this module to build query string (like http_build_query() in php).
Installation:
Usage:
const http_build_query = require('js-http-build-query') // Simple object let data = roll: 143, message: 'hello world', url: 'https://example.com' > http_build_query(data) // roll=143&message=world&url=https://example.com let complexData = foo: "bar", items: salt: "suger", quantity: [2, 3, 4] > > http_build_query(complexData) // foo=bar&items[salt]=suger&items[quantity][0]=2&items[quantity][1]=3&items[quantity][2]=4
Contributing
Security Vulnerabilities
If you discover a security vulnerability or bugs, please send an e-mail to Muhaimenul Islam via i.muhaimen@gmail.com.
License
The js-http-build-query package is open-sourced project licensed under the MIT license.
Курсы javascript
Эта функция не поддерживает вложенные массивы, поэтому не может считаться полноценным аналогом.
ведь select может содержать несколько полей, а ключ в хеше может быть только один, мы не сможем написать нечто подобное:
да и php’шная оригинальная функа правильно обрабатывает вложенные массивы.
так чта незачет.
Ну для вложенных массивов/объектов рекурсия ещё нужна
Для тех кто ищет способ обмениваться массивами через GET запрос.
// // JS // var Object = <>; Object.Article = []; Object.Article.push(); Object.Article.push(); var JsonStr = JSON.stringify(Object); window.location.href = window.location.href + '?object=' + encodeURIComponent(JsonStr);
// // PHP // $InputString = isset($_GET['object']) ? urldecode($_GET['object']) : null; $Object = json_decode($InputString, true);
Используйте jQuery.param() либо стяните исходник
Отправить комментарий
- Полезные.
- Дополняющие прочитанное.
- Вопросы по прочитанному. Именно по прочитанному, чтобы ответ на него помог другим разобраться в предмете статьи. Другие вопросы могут быть удалены.
Для остальных вопросов и обсуждений есть форум.
Учебник javascript
Основные элементы языка
Сундучок с инструментами
Интерфейсы
Все об AJAX
Оптимизация
Разное
- Асинхронное программирование
- Google Gears в деталях
- Javascript Flash мост
- Букмарклеты и правила их написания
- О подборке книг на сайте
- Почему — плохо
- Способы идентификации в интернете
- Уровни DOM
- Что почитать?
- Шаблонизация с javascript
- Юнит-тесты уровня браузера на связке Selenium + PHP.
- Справочники: Javascript/HTML/CSS
- Система сборки и зависимостей Google Closure Library
- Хранение данных на клиенте. DOM Storage и его аналоги.
- 10 лучших функций на JavaScript
- Hello, this weekend is good for me.
20 минут 17 секунд назад - Cricket lovers always seem to look for.
22 минуты 35 секунд назад - Latest news and updates on cricket, IPL.
23 минуты 32 секунды назад - Thank you for posting your article.
2 часа 19 минут назад - Good site! I genuinely love how it is.
3 часа 4 минуты назад - All of the emoji characters are now.
4 часа 38 минут назад - DOM представляет каждый элемент на.
6 часов 31 минута назад - Join us as we สล็อต ฝากถอน true wallet.
7 часов 1 минута назад - You can certainly see your enthusiasm.
11 часов 22 минуты назад - Хорошая статья, которая меня кое-чему.
12 часов 57 минут назад
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A JavaScript package to generate HTTP Query String from Object
License
muhaimenul/js-http-build-query
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A simple JavaScript package to generate URL-encoded HTTP Query String. Just create a object using query parameters and their values, and pass the object through this module to build query string (like http_build_query() in php).
const http_build_query = require('js-http-build-query') // Simple object let data = roll: 143, message: 'hello world', url: 'https://example.com' > http_build_query(data) // roll=143&message=world&url=https://example.com let complexData = foo: "bar", items: salt: "suger", quantity: [2, 3, 4] > > http_build_query(complexData) // foo=bar&items[salt]=suger&items[quantity][0]=2&items[quantity][1]=3&items[quantity][2]=4
If you discover a security vulnerability or bugs, please send an e-mail to Muhaimenul Islam via i.muhaimen@gmail.com.
The js-http-build-query package is open-sourced project licensed under the MIT license.
About
A JavaScript package to generate HTTP Query String from Object
PHP’s http_build_query in JavaScript
Here’s what our current JavaScript equivalent to PHP’s http_build_query looks like.
module.exports = function http_build_query (formdata, numericPrefix, argSeparator, encType) { // eslint-disable-line camelcase// discuss at: https://locutus.io/php/http_build_query/// original by: Kevin van Zonneveld (https://kvz.io)// improved by: Legaev Andrey// improved by: Michael White (https://getsprink.com)// improved by: Kevin van Zonneveld (https://kvz.io)// improved by: Brett Zamir (https://brett-zamir.me)// revised by: stag019// input by: Dreamer// bugfixed by: Brett Zamir (https://brett-zamir.me)// bugfixed by: MIO_KODUKI (https://mio-koduki.blogspot.com/)// improved by: Will Rowe// note 1: If the value is null, key and value are skipped in the// note 1: http_build_query of PHP while in locutus they are not.// example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&')// returns 1: 'foo=bar&php=hypertext+processor&baz=boom&cow=milk'// example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_')// returns 2: 'myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&php=hypertext+processor&cow=milk'// example 3: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&', 'PHP_QUERY_RFC3986')// returns 3: 'foo=bar&php=hypertext%20processor&baz=boom&cow=milk'let encodeFuncswitch (encType) {case 'PHP_QUERY_RFC3986':encodeFunc = require('../url/rawurlencode')breakcase 'PHP_QUERY_RFC1738':default:encodeFunc = require('../url/urlencode')break}let valuelet keyconst tmp = []var _httpBuildQueryHelper = function (key, val, argSeparator) {let kconst tmp = []if (val === true) {val = '1'} else if (val === false) {val = '0'}if (val !== null) {if (typeof val === 'object') {for (k in val) {if (val[k] !== null) {tmp.push(_httpBuildQueryHelper(key + '[' + k + ']', val[k], argSeparator))}}return tmp.join(argSeparator)} else if (typeof val !== 'function') {return encodeFunc(key) + '=' + encodeFunc(val)} else {throw new Error('There was an error processing for http_build_query().')}} else {return ''}}if (!argSeparator) {argSeparator = '&'}for (key in formdata) {value = formdataHttp build query javascriptif (numericPrefix && !isNaN(key)) {key = String(numericPrefix) + key}const query = _httpBuildQueryHelper(key, value, argSeparator)if (query !== '') {tmp.push(query)}}return tmp.join(argSeparator)}
How to use
You you can install via npm install locutus and require it via require(‘locutus/php/url/http_build_query’) . You could also require the url module in full so that you could access url.http_build_query instead.
If you intend to target the browser, you can then use a module bundler such as Parcel, webpack, Browserify, or rollup.js. This can be important because Locutus allows modern JavaScript in the source files, meaning it may not work in all browsers without a build/transpile step. Locutus does transpile all functions to ES5 before publishing to npm.
A community effort
Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we don’t consider it to be a bad thing that many of our functions are first iterations, which may still have their fair share of issues. We hope that these flaws will inspire others to come up with better ideas.
This way of working also means that we don’t offer any production guarantees, and recommend to use Locutus inspiration and learning purposes only.
Notes
- If the value is null, key and value are skipped in the http_build_query of PHP while in locutus they are not.
Examples
Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.
# | code | expected result |
---|---|---|
1 | http_build_query(, », ‘&’) | ‘foo=bar&php=hypertext+processor&baz=boom&cow=milk’ |
2 | http_build_query(, ‘myvar_’) | ‘myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&php=hypertext+processor&cow=milk’ |
3 | http_build_query(, », ‘&’, ‘PHP_QUERY_RFC3986’) | ‘foo=bar&php=hypertext%20processor&baz=boom&cow=milk’ |