简体   繁体   中英

Why is my jQuery AJAX Call Opening the Response in the Browser?

I'm completely new to PHP, Javascript, jQuery etc. so I'm finding this very confusing.

I have written a php file that echoes JSON code. I'm then trying to store this response into a Javascript variable on the client, like so:

var res;
$.getJSON("my_php_file", { some_param: "param" },
      function(data) {
         res = data;
      }
});

Instead, the web browser just opens the response JSON in the current window, rather than saving the result to res . Why is this?

Thanks

Are you handling an onClick event on a link? If so then you are not stopping the event propagation (the default behaviour).

$('a#msome_link').click(function(e) {
    e.preventDefault();

    var res;
    $.getJSON("my_php_file", { some_param: "param" },
        function(data) {
            res = data;
        }
    });

    return(false); // this is not necessary any more in modern browsers
});
  1. make sure my_php_file returns Content-Type: application/json; charset=<your charset> Content-Type: application/json; charset=<your charset> header
  2. provide json callback:

    my_php_file?cb=?

  3. make sure my_php_file responds appropriately:

    printf("%s(%s)", $_GET['cb'], $json_response);

  4. consider @Mihai Stancu's answer (should be number 0, actually :) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM