Pagina 1 din 1

Array cu parti din url din javascript la php

Scris: Lun Feb 08, 2016
de ionatan
Salut,
Se poate face cu javascript un array cu fiecare parte din adresa url a pagini, ca apoi sa-l folosesc in php ?

Array cu parti din url din javascript la php

Scris: Lun Feb 08, 2016
de MarPlo
Salut
Se poate face array /obiect in javascript cu parti din url. Dar ca sa-l folosesti in php, trebuie trimis in format JSON cu o functie Ajax din javascript la php.
Ca sa preiei datele din url intr-un obiect in jS poti sa folosesti functia urlData() din acest exemplu:

Cod: SelectaĊ£i tot

<script>
// Extract data from URL address
// Returns an object with parts of the URL address:
// {protocol, domain-name, port, path, file-name, search-string, search-object, hash}
function urlData(url){ // From: https://coursesweb.net/javascript/
  // object for data that will be returned
  var re = {protocol:'', domain:'', port:80, path:'', file:'', search_str:'', search_obj:{}, hash:''};

  // creates an anchor element, and adds the url in "href" attribute
  var a_elm  = document.createElement('a');
  a_elm.href = url;

  // adds URL data in re object, and returns it
  re.protocol = a_elm.protocol.replace(':', '');
  re.domain = a_elm.hostname.replace('www.', '');
  if(a_elm.port !='') re.port = a_elm.port;
  re.path = a_elm.pathname;
  if(a_elm.pathname.match(/[^\/]+[\.][a-z0-9]+$/i) != null) re.file = a_elm.pathname.match(/[^\/]+[\.][a-z0-9]+$/i)[0];
  re.search_str = a_elm.search.replace('?', '');

  // get search-data into an object {name:value}, in case the are multiple pairs name=value
  var src_data = re.search_str.split('&');
  for(var i=0; i<src_data.length; i++){
    var ar_val = src_data[i].split('=');   // separate name and value from each pair
    re.search_obj[ar_val[0]] = ar_val[1];
  }

  re.hash = a_elm.hash.replace('#', '');  //get #hash part
  return re;
}

// Test
var url = 'https://coursesweb.net:80/javascript/index.php?pg=tutorial&id=89#hash_part';
var url_data = urlData(url);

// convert url_data in json and show it in alert()
url_data = JSON.stringify(url_data);
alert(url_data);
/*Result this string:
 {"protocol":"http", "domain":"coursesweb.net", "port":80, "path":"/javascript/index.php", "file":"index.php", "search_str":"pg=tutorial&id=89", "search_obj":{"pg":"tutorial","id":"89"}, "hash":"hash_part"}
*/
</script>
- Mai departe, se trimite sirul din "url_data" cu ajax la php, iar in php il preiei si prelucrezi datele din el cum stii.