dynamic url in ajax

3

How do I get Ajax to get the current URL? For in it are the values that go to php. If I do it works like this

  jQuery.ajax({
    url: "http://localhost/jogoteocratico/consulta.php?dificuldade=1&rodada=1",
    type: "GET",
    dataType: 'json',
    success: function(returnjson) {
    var i=0;
     $('#proxima').click(function exibir(){
       i++;
       document.getElementById("id_pergunta").innerHTML = returnjson[i].id_pergunta;
       document.getElementById("pergunta_jogo").innerHTML = returnjson[i].pergunta;
       document.getElementById("desafio_jogo").innerHTML = returnjson[i].desafio;
       document.getElementById("resposta_jogo").innerHTML = returnjson[i].resposta;

     });

But if I do, it does not work:

$(document).ready(function mostrarPergunta(){
  var url = window.location.href;
  jQuery.ajax({
        url: url,
        type: "GET",
        dataType: 'json',
        success: function(returnjson) {
        //  for(i=0; i<returnjson.length; i++){
          //  alert(returnjson[i].pergunta);
         //}
        var i=0;
         $('#proxima').click(function exibir(){
           i++;
           document.getElementById("id_pergunta").innerHTML = returnjson[i].id_pergunta;
           document.getElementById("pergunta_jogo").innerHTML = returnjson[i].pergunta;
           document.getElementById("desafio_jogo").innerHTML = returnjson[i].desafio;
           document.getElementById("resposta_jogo").innerHTML = returnjson[i].resposta;

         });
    
asked by anonymous 28.01.2017 / 19:51

2 answers

6

You can use location.search to fetch the querystring from the URL ( ), e depois usar caminhos relativos, sem .

It would look like this:

jQuery.ajax({
    url: "/jogoteocratico/consulta.php" + location.search,
    type: "GET",
    dataType: 'json',
    success: function(returnjson) {
    
28.01.2017 / 21:58
3
var url = window.location.href;

jQuery.ajax({

  url: url,
  //outras coisas vão aqui

});  

The call to window.location.href will get the current url of the page. Pass this to the ajax method call and you will have a "dynamic reference" to the current page url;

    
28.01.2017 / 21:35