dynamic url in ajax

Asked

Viewed 4,034 times

3

How do I get Ajax to get the current URL? Here are the values that go to php. If I do so it works

  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 like this, it doesn’t 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;

         });
  • What is the difference between the two examples? To use the current query string you can do url: "/jogoteocratico/consulta.php" + location.search,

  • @Thank you very much.

2 answers

6


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

Would look like this:

jQuery.ajax({
    url: "/jogoteocratico/consulta.php" + location.search,
    type: "GET",
    dataType: 'json',
    success: function(returnjson) {
  • 1

    I edited the question by putting the code that didn’t work, but here’s the addendum that your answer worked. ;)

3

var url = window.location.href;

jQuery.ajax({

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

});  

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

  • I did so, gave an Alert in the url, ta picking right, but returns me internal error server,

  • @Tiagosilveira Now this is not the fault of the request made by Ajax. That’s something in your code in the back end. Now you need to debug your code to see what’s wrong with it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.