Javascript/jQuery yordamida URLda so'rov parametrini qanday qo'shish yoki o'zgartirish mumkin?

JQuery 1.12 dan foydalanmoqdaman. So'rovlar qatori parametrini oynamning URL so'rovining satrida o'zgartirmoqchiman yoki avval mavjud bo'lmagan parametrni qo'shmoqchiman. Men quyida sinab ko'rdim:

new_url = window.location.href.replace( /[\?#].*|$/, "?order_by=" + data_val )  
window.location.href = new_url 

Lekin men kashf qiladigan narsa bu men istamagan so'rovlar qatoridagi barcha oldingi parametrlarni o'chirib tashlashidir. So'rovlar qatori bo'lsa:

?a=1&b=2

Yangi so'rovlar qatori bo'lishini istayman:

?a=2&b=2&order_by=data

va so'rovlar qatori bo'lsa:

?a=2&b=3&order_by=old_data

u shunday bo'lar edi:

?a=2&b=3&order_by=data
7
Faqat bilish uchun ... nimani kutmoqdasiz "vazifasini bajarish kerak"?
qo'shib qo'ydi muallif Lelio Faieta, manba
bu kabi holatda bo'sh yoki yaroqsiz (masalan, noto'g'ri eski so'rovlar parametri) bo'lsa, eski so'rov parametringizni, yangi so'rov parametrini va yangi so'rov parametr qiymatini tekshirishingiz kerak. Shuningdek, joriy urlning so'rov parametrlari mavjudligini tekshirishingiz kerak. Ko'pincha so'rov parametr funktsiyasini qo'shish yoki almashtirishda bajarilishi kerak bo'lgan cheklar
qo'shib qo'ydi muallif Peter Darmis, manba
Ushbu savolga diqqat qiling: stackoverflow.com/questions/5999118 /; hellip;
qo'shib qo'ydi muallif Hristiyan Dodov, manba

9 javoblar

Yaxshi echim quyidagilardan iborat bo'lishi kerak:

  1. order_by so'rov parametresi allaqachon mavjud bo'lgan URL, agar ixtiyoriy tenglik belgisi oldin bo'shliqlar bilan. order_by so'rovlar dizgesinin boshida, oxirida yoki oxirida paydo bo'ladigan holatlarga qo'shimcha ravishda ajratish mumkin.
  2. Hech bo'lmaydigan URL va order_by so'rov parametresi, ammo so'rovlar mag'lubiyatini cheklash uchun savol belgisi mavjud.
  3. Hech bo'lmaydigan URL va order_by so'rov parametresi va so'rovlar mag'lubiyatini cheklash uchun savol belgisi yo'q.

Yuqoridagi holatlarda quyidagilar muhokama qilinadi:

  if (/[?&]order_by\s*=/.test(oldUrl)) {
    newUrl = oldUrl.replace(/(?:([?&])order_by\s*=[^?&]*)/, "$1order_by=" + data_val);
  } else if (/\?/.test(oldUrl)) {
    newUrl = oldUrl + "&order_by=" + data_val;
  } else {
    newUrl = oldUrl + "?order_by=" + data_val;
  }

quyida ko'rsatilganidek:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

getNewUrl("?a=1&b=2");
getNewUrl("?a=2&b=3&order_by=old_data");
getNewUrl("?a=2&b=3&order_by = old_data&c=4");
getNewUrl("?order_by=old_data&a=2&b=3");
getNewUrl("http://www.stackoverflow.com");

function getNewUrl(oldUrl) {
  var data_val = "new_data";
  var newUrl;
  if (/[?&]order_by\s*=/.test(oldUrl)) {
    newUrl = oldUrl.replace(/(?:([?&])order_by\s*=[^?&]*)/, "$1order_by=" + data_val);
  } else if (/\?/.test(oldUrl)) {
    newUrl = oldUrl + "&order_by=" + data_val;
  } else {
    newUrl = oldUrl + "?order_by=" + data_val;
  }
  console.log(oldUrl + "\n...becomes...\n" + newUrl);
}  
</div> </div>
4
qo'shib qo'ydi

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

function addOrReplaceOrderBy(newData) {
  var stringToAdd = "order_by=" + newData;

  if (window.location.search == "")
    return window.location.href + stringToAdd;

  if (window.location.search.indexOf('order_by=') == -1)
    return window.location.href + stringToAdd;

  var newSearchString = "";
  var searchParams = window.location.search.substring(1).split("&");
  for (var i = 0; i < searchParams.length; i++) {
    if (searchParams[i].indexOf('order_by=') > -1) {
      searchParams[i] = "order_by=" + newData;
      break;
    }
  }
  return window.location.href.split("?")[0] + "?" + searchParams.join("&");
}

window.location.href = addOrReplaceOrderBy("new_order_by");
</div> </div>

Biroz uzoq bo'lsa-da, lekin o'ylaymanki, u maqsadga muvofiq ishlaydi.

3
qo'shib qo'ydi

JQuery plaginini siz uchun barcha og'ir yukni ko'tarish uchun ishlatishingiz mumkin. So'rovlar satrini ajralib chiqadi va siz uchun yangilangan so'rovlar qatorini qayta yaratadi. Juda kam kod bilan shug'ullanish uchun.

Plugin Download Page
Github Repo

// URL: ?a=2&b=3&order_by=old_data

var order_by = $.query.get('order_by');
//=> old_data

// Conditionally modify parameter value
if (order_by) { 
  order_by = “data”;
}

// Inject modified parameter back into query string
var newUrl = $.query.set(“order_by”, order_by).toString();
//=> ?a=2&b=3&order_by=data

Node.js dan foydalanish uchun NPMda mavjud bo'lgan paket mavjud.

NPM Package
Github Repo

var queryString = require('query-string');
var parsed = queryString.parse('?a=2&b=3&order_by=old_data'); //location.search

// Conditionally modify parameter value
if (parsed.order_by) {
  parsed.order_by = 'data';
}

// Inject modified parameter back into query string
const newQueryString = queryString.stringify(parsed);
//=> a=2&b=3&order_by=data
3
qo'shib qo'ydi
Xuddi shu ishni bajaradigan jQuery plaginlari mavjud. Quyidagini yuklab olishingiz mumkin: plugins.jquery.com/query-object . Ushbu sahifadagi "Hujjatlarni o'qing" linki sizni github repo-ga ko'rsatib, so'rovlar mag'lubiyatini ajralish va manipulyatsiya qilish uchun ko'plab misollar mavjud. Menga bu ehtiyojni qondiradimi yoki yo'qligini bilib qo'ying, men javobimni o'zgartiraman.
qo'shib qo'ydi muallif grizzthedj, manba
Javobni jQuery plaginlari haqida ma'lumotni kiritish uchun yangiladim.
qo'shib qo'ydi muallif grizzthedj, manba
Men jQuery (1.12) dan foydalanmoqdaman. JQuery'da bu bilan bog'liq plagin bormi?
qo'shib qo'ydi muallif user7055375, manba

Buni ko'ring:

Parametrlarni o'qish uchun:<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

const data = ['example.com?var1=value1&var2=value2&var3=value3', 'example.com?a=2&b=2&order_by=data']

const getParameters = url => {
  const parameters = url.split('?')[1],
        regex = /(\w+)=(\w+)/g,
        obj = {}
  let temp
  while (temp = regex.exec(parameters)){
    obj[temp[1]] = decodeURIComponent(temp[2])
  }
  return obj
}

for(let url of data){
  console.log(getParameters(url))
}
</div> </div>

Faqat ushbu parametrlarni joylashtirish uchun:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

const data = ['example.com?zzz=asd']
const parameters = {a:1, b:2, add: "abs"}

const setParameters = (url, parameters) => {
  const keys = Object.keys(parameters)
  let temp = url.split('?')[0] += '?'
  for (let i = 0; i < keys.length; i++) {
    temp += `${keys[i]}=${parameters[keys[i]]}${i  == keys.length - 1 ? '' : '&'}`
  }
  return temp
}

for (let url of data){
  console.log(setParameters(url, parameters))
}
</div> </div>

Va qo'shib qo'yish uchun (yoki mavjud bo'lsa)

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

const data = ['example.com?a=123&b=3&sum=126']
const parameters = {order_by: 'abc', a: 11}
const insertParameters = (url, parameters) => {
  const keys = Object.keys(parameters)
  let result = url
  for (let i = 0; i < keys.length; i++){
    if (result.indexOf(keys[i]) === -1) {
      result += `&${keys[i]}=${encodeURIComponent(parameters[keys[i]])}`
    } else {
      let regex = new RegExp(`${keys[i]}=(\\w+)`)
      result = result.replace(regex, `&${keys[i]}=${encodeURIComponent(parameters[keys[i]])}`)
    }
  }
  return result
}

for (let url of data){
  console.log(insertParameters(url, parameters))
}
</div> </div>

Hope this works for you ;) After using function just replace window.location.href

1
qo'shib qo'ydi

Bu kichik funktsiya yordam berishi mumkin.

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

function changeSearchQueryParameter(oldParameter,newParameter,newValue) {
var parameters = location.search.replace("?", "").split("&").filter(function(el){ return el !== "" });
var out = "";
var count = 0;
if(oldParameter.length>0) {
if(newParameter.length>0 && (newValue.length>0 || newValue>=0)){
        out += "?";
        var params = [];
        parameters.forEach(function(v){
                var vA = v.split("=");
                if(vA[0]==oldParameter) {
                        vA[0]=newParameter;
                        if((newValue.length>0 || newValue>=0)) {
                        vA[1] = newValue;                       
                        }
                } else {
                        count++;
                }
                params.push(vA.join("="));      
        });
        if(count==parameters.length) {
                params.push([newParameter,newValue].join("="));
        }
  params = params.filter(function(el){ return el !== "" });
  if(params.length>1) {
  out += params.join("&");
  } 
  if(params.length==1) {
  out += params[0];
  }     
 }
} else {
if((newParameter.length>0) && (newValue.length>0 || newValue>=0)){
if(location.href.indexOf("?")!==-1) {
var out = "&"+newParameter+"="+newValue;        
} else {
var out = "?"+newParameter+"="+newValue;        
}
}
}
return location.href+out;
}
// if old query parameter is declared but does not exist in url then new parameter and value is simply added if it exists it will be replaced
console.log(changeSearchQueryParameter("ib","idx",5));
// add new parameter and value in url
console.log(changeSearchQueryParameter("","idy",5));
// if no new or old parameter are present url does not change
console.log(changeSearchQueryParameter("","",5));
console.log(changeSearchQueryParameter("","",""));
</div> </div>
1
qo'shib qo'ydi

shunga o'xshash narsa?

new_url = "";

if(window.location.search && window.location.search.indexOf('order_by=') != -1)
  new_url = window.location.search.replace( /order_by=\w*\d*/, "order_by=" + data_val);
else if(window.location.search)
  new_url = window.location.search + "&order_by=" + data_val;
else
  new_url = window.location.search + "?order_by=" + data_val;

window.location.href = new_url;
1
qo'shib qo'ydi
Yangilangan kodni tekshiring, iltimos
qo'shib qo'ydi muallif Georgiy Dubrov, manba
@Natalia siz haqsiz, qo'shimcha shart, yangi kod yuqorida
qo'shib qo'ydi muallif Georgiy Dubrov, manba
@Natalia emas, balki, chunki regexpda kodlashni faqat raqamli va mag'lubiyat belgilarini o'zgartirish uchun va% yoki _
qo'shib qo'ydi muallif Georgiy Dubrov, manba
Salom, bu ishlamayapti. A = 1 & b = 2 & order_by = new_data, "a = 1 & b = 2 & order_by = nima bo'lsa & order_by = new_data" so'zi so'rovlar qatori "a = 1 & b = 2 & order_by =
qo'shib qo'ydi muallif user7055375, manba
Bu hali ham ishlamaydi. Agar so'rovlar majmuasi "order_by" ni o'z ichiga olmasa, u yuqoridagi kodni chaqirib qo'shilmaydi.
qo'shib qo'ydi muallif user7055375, manba
Rahmat. Buni bir yoki ikki qatorga qisqartirishning biron bir usuli bormi? Bu juda uzoq ko'rinadi
qo'shib qo'ydi muallif user7055375, manba
Yaxshiyamki, mavjud satrlar ishlamaydi. So'rovlar satri "a & order_by = abc% 20desc" bo'lsa, order_by param o'zgarmaydi. O'ylaymanki, biz bulardan voz kechishimiz kerak.
qo'shib qo'ydi muallif user7055375, manba

Regex modelini ishlatish uchun men buni afzal ko'rmoqdaman:

var oldUrl = "http://stackoverflow.com/";
var data_val = "newORDER" ;
var r = /^(.+order_by=).+?(&|$)(.*)$/i ;
var newUrl = "";

var matches = oldUrl.match(r) ;
if(matches===null){
  newUrl = oldUrl + ((oldUrl.indexOf("?")>-1)?"&":"?") + "order_by=" + data_val ;
}else{
  newUrl = matches[1]+data_val+matches[2]+matches[3] ;
}
conole.log(newUrl);

If no order_by exist, matches is null and order_by=.. should come after ? or & (if other parameters exist, new one needs &).

If order_by exist, matches has 3 items, see here

1
qo'shib qo'ydi

You can remove parameter from query string using URLSearchParams https://developer.mozilla.org/ru/docs/Web/API/URLSearchParams?param11=val

It is not yet supported by IE and Safari, but you can use it by adding polyfill https://github.com/jerrybendy/url-search-params-polyfill

Va URIning so'rovlar qismiga kirish yoki o'zgartirish uchun window.location ning "search" xususiyatidan foydalaning.

Ish kodi namunasi:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

  var a = document.createElement("a")
  a.href = "http://localhost.com?param1=val&param2=val2&param3=val3#myHashCode";
  var queryParams = new URLSearchParams(a.search)
  queryParams.delete("param2")
  a.search = queryParams.toString();
  console.log(a.href);
</div> </div>
1
qo'shib qo'ydi

Ehtimol, siz faqat siz izlayotgan qiymatlarni olish uchun oddiy ifodani tweaking, keyin esa ularni yordamchi funktsiyadagi qo'shishingiz yoki ularni yangilashingiz mumkin:

function paramUpdate(param) {

  var url = window.location.href,
      regExp = new RegExp(param.key + '=([a-z0-9\-\_]+)(?:&)?'),
      existsMatch = url.match(regExp);

  if (!existsMatch) {
      return url + '&' + param.key + '=' + param.value
  }

  var paramToUpdate = existsMatch[0],
      valueToReplace = existsMatch[1],
      updatedParam = paramToUpdate.replace(valueToReplace, param.value);

  return url.replace(paramToUpdate, updatedParam);
}

var new_url = paramUpdate({
    key: 'order_by',
    value: 'id'
});
window.location.href = new_url;

Umid qilamanki, bu sizning ehtiyojlaringiz uchun yaxshi ishlaydi!

1
qo'shib qo'ydi
Javascript UZB
Javascript UZB
99 ishtirokchilar

@js_uzb @vuejs_uz @react_uz @nodejs_uz @angular_uz @ngTashkent @yiiframework_uz @laravel_uz @linux_uzbek @python_uz @swift_uzb —————— @uzdevgroup @UzGeeksGroup ——— @UzDev_Jobs @jobs_uzb