简体   繁体   中英

jQuery ajax call failing

I'm having some issues with jQuery AJAX calls. I'm by no means an expert but I know jQuery enough to get by with simple tasks.

Here is my code -

var id = 123;
    var url = "/test.aspx?id=" + id;
            $.getJSON(url, function (data) {
                alert(1);
            });

The problem is that the alert(1) is not getting hit. When I check for [domain]/test.aspx?id=123 manually, I'm getting JSON data back. What am I doing wrong here or how can I diagnose the issue here?

Thanks

Your example works perfectly fine. Here is a JSfiddle example to test it (using the echo service):

var id = 123;
var url = "/echo/json/";
$.getJSON(url, function (data) {
    alert("hello");
});

http://jsfiddle.net/QyfCF/1/

This looks like a problem coming from somewhere other than the code you've provided. To troubleshoot, I'd try doing something like this...

var id = 123;
var url = "/test.aspx?id=" + id;
console.log("before");
$.getJSON(url, function (data) {
  console.log("inside");
});
console.log("after");

That way you can see whether the code actually ever gets to the json request because you'll see "before" in the console, you can see whether it gets inside because you'll see "inside" in the console, etc.

Also, it's possible that the url your passing into $.getJSON isn't the correct url. You might wanna try it without the slash beforehand, or possibly pass in the full url to make sure you're referencing the right place.

It's a little strange but I had to specify a data type of JSON in the request.

var id = 123; var url = "/echo/json/"; $.getJSON(url, "json", function (data) { alert("hello"); });

I got the idea of JSON from http://api.jquery.com/jQuery.getJSON/ . The example on this page was for PlainObject. The url in my code was trying to parse JSON as PlainObject but failing. I used .success and .error after closing bracket of getJSON to figure out the issue. To see how success and error can be used scroll to the bottom of the jquery.com link.

Make sure that your JSON is valid JSON, eg by running it though JSONLint . JQuery's .getJSON() and .ajax() silently fail when the requested JSON is not valid.

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