Ajax request fails, can't see why

亡梦爱人 提交于 2019-12-04 18:07:27
$.ajax({
    /* ajax options omitted */
    error: function (xmlHttpRequest, textStatus, errorThrown) {
         if(xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0) 
              return;  // it's not really an error
         else
              // Do normal error handling
});
Tadeck

What is probably the problem

I think I know your problem here. Seemingly you are loading a page one some protocol+domain+port (eg. "http://localhost/"), but then invoke AJAX request to a different protocol, domain or port (in this case probably only port differs: "http://localhost:8000/products").

This way you are probably hitting Same Origin Policy limitation, which is security feature of your browser. In such cases browsers may indicate that specific request has been "cancelled" (because browser blocked it).

Solution

There are multiple solutions to your problem:

  • (easiest) stick to the same protocol+domain+port for both original site and the endpoint requested by AJAX,
  • (second easiest) build an end point on the server, so eg. "http://localhost/products" will call "http://localhost:8000/products" in the background and will return its response (as a walkaround for SOP),
  • some more complex solutions like JSONP, CORS etc. (more here: https://stackoverflow.com/a/8467697/548696),

Try using just

$.ajax({
  url: "http://localhost:8000/products", 
  dataType: 'json',
  success: function(data){
            console.log("You made it!");
        },
        error: function(xhr) {
           console.log("Error: " + xhr.statusText);
       }
});

Instead of using done callback , you can use code line inside success or complete callback. Its quite simple and cleaner.

Why dont you try and merge the two ajax calls in one. and also try and change type = "POST"

$.ajax({
    type: "POST",
    url: "http://localhost:8000/products",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    error: function(errMsg) {
        alert(errMsg);
    }
});

I think your browser cached the error, or may be there are problems in setting headers properly, so try adding this way over there in the $.ajaxsetup():

    $.ajaxSetup ({
      url: "http://localhost:8000/products", // <--- returns json
      type: "GET",
      dataType: 'json',
      cache: false,
      contentType: "application/json"
    });

try this way once and see if works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!